python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <libdivecomputer/units.h> #include "suunto_eon.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &suunto_eon_parser_vtable) typedef struct suunto_eon_parser_t suunto_eon_parser_t; struct suunto_eon_parser_t { dc_parser_t base; int spyder; // Cached fields. unsigned int cached; unsigned int divetime; unsigned int maxdepth; unsigned int marker; unsigned int nitrox; }; static dc_status_t suunto_eon_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t suunto_eon_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t suunto_eon_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t suunto_eon_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t suunto_eon_parser_vtable = { sizeof(suunto_eon_parser_t), DC_FAMILY_SUUNTO_EON, suunto_eon_parser_set_data, /* set_data */ suunto_eon_parser_get_datetime, /* datetime */ suunto_eon_parser_get_field, /* fields */ suunto_eon_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; static dc_status_t suunto_eon_parser_cache (suunto_eon_parser_t *parser) { dc_parser_t *abstract = (dc_parser_t *) parser; const unsigned char *data = parser->base.data; unsigned int size = parser->base.size; if (parser->cached) { return DC_STATUS_SUCCESS; } if (size < 13) { return DC_STATUS_DATAFORMAT; } // The Solution Nitrox/Vario stores nitrox data, not tank pressure. unsigned int nitrox = !parser->spyder && (data[4] & 0x80); // Parse the samples. unsigned int interval = data[3]; unsigned int nsamples = 0; unsigned int depth = 0, maxdepth = 0; unsigned int offset = 11; while (offset < size && data[offset] != 0x80) { unsigned char value = data[offset++]; if (value < 0x7d || value > 0x82) { depth += (signed char) value; if (depth > maxdepth) maxdepth = depth; nsamples++; } } // Check the end marker. unsigned int marker = offset; if (marker + 2 >= size || data[marker] != 0x80) { ERROR (abstract->context, "No valid end marker found!"); return DC_STATUS_DATAFORMAT; } // Cache the data for later use. parser->divetime = nsamples * interval; parser->maxdepth = maxdepth; parser->marker = marker; parser->nitrox = nitrox; parser->cached = 1; return DC_STATUS_SUCCESS; } dc_status_t suunto_eon_parser_create (dc_parser_t **out, dc_context_t *context, int spyder) { suunto_eon_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (suunto_eon_parser_t *) dc_parser_allocate (context, &suunto_eon_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->spyder = spyder; parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; parser->marker = 0; parser->nitrox = 0; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t suunto_eon_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { suunto_eon_parser_t *parser = (suunto_eon_parser_t *) abstract; // Reset the cache. parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; parser->marker = 0; parser->nitrox = 0; return DC_STATUS_SUCCESS; } static dc_status_t suunto_eon_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { suunto_eon_parser_t *parser = (suunto_eon_parser_t *) abstract; if (abstract->size < 6 + 5) return DC_STATUS_DATAFORMAT; const unsigned char *p = abstract->data + 6; if (datetime) { if (parser->spyder) { datetime->year = p[0] + (p[0] < 90 ? 2000 : 1900); datetime->month = p[1]; datetime->day = p[2]; datetime->hour = p[3]; datetime->minute = p[4]; } else { datetime->year = bcd2dec (p[0]) + (bcd2dec (p[0]) < 85 ? 2000 : 1900); datetime->month = bcd2dec (p[1]); datetime->day = bcd2dec (p[2]); datetime->hour = bcd2dec (p[3]); datetime->minute = bcd2dec (p[4]); } datetime->second = 0; datetime->timezone = DC_TIMEZONE_NONE; } return DC_STATUS_SUCCESS; } static dc_status_t suunto_eon_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { suunto_eon_parser_t *parser = (suunto_eon_parser_t *) abstract; const unsigned char *data = abstract->data; // Cache the data. dc_status_t rc = suunto_eon_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; dc_gasmix_t *gasmix = (dc_gasmix_t *) value; dc_tank_t *tank = (dc_tank_t *) value; unsigned int oxygen = 21; unsigned int beginpressure = 0; unsigned int endpressure = 0; if (parser->nitrox) { oxygen = data[0x05]; } else { beginpressure = data[5] * 2; endpressure = data[parser->marker + 2] * 2; } if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = parser->divetime; break; case DC_FIELD_MAXDEPTH: *((double *) value) = parser->maxdepth * FEET; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = 1; break; case DC_FIELD_GASMIX: gasmix->helium = 0.0; gasmix->oxygen = oxygen / 100.0; gasmix->nitrogen = 1.0 - gasmix->oxygen - gasmix->helium; break; case DC_FIELD_TANK_COUNT: if (beginpressure == 0 && endpressure == 0) *((unsigned int *) value) = 0; else *((unsigned int *) value) = 1; break; case DC_FIELD_TANK: tank->type = DC_TANKVOLUME_NONE; tank->volume = 0.0; tank->workpressure = 0.0; tank->gasmix = 0; tank->beginpressure = beginpressure; tank->endpressure = endpressure; break; case DC_FIELD_TEMPERATURE_MINIMUM: if (parser->spyder) *((double *) value) = (signed char) data[parser->marker + 1]; else *((double *) value) = data[parser->marker + 1] - 40; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t suunto_eon_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { suunto_eon_parser_t *parser = (suunto_eon_parser_t *) abstract; const unsigned char *data = abstract->data; unsigned int size = abstract->size; dc_sample_value_t sample = {0}; // Cache the data. dc_status_t rc = suunto_eon_parser_cache (parser); if (rc != DC_STATUS_SUCCESS) return rc; // Time sample.time = 0; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Depth (0 ft) sample.depth = 0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); // Initial gas mix. sample.gasmix = 0; if (callback) callback (DC_SAMPLE_GASMIX, sample, userdata); unsigned int depth = 0; unsigned int time = 0; unsigned int interval = data[3]; unsigned int complete = 1; unsigned int offset = 11; while (offset < size && data[offset] != 0x80) { unsigned char value = data[offset++]; if (complete) { // Time (seconds). time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); complete = 0; } if (value < 0x7d || value > 0x82) { // Delta depth. depth += (signed char) value; // Depth (ft). sample.depth = depth * FEET; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); complete = 1; } else { // Event. sample.event.type = SAMPLE_EVENT_NONE; sample.event.time = 0; sample.event.flags = 0; sample.event.value = 0; switch (value) { case 0x7d: // Surface sample.event.type = SAMPLE_EVENT_SURFACE; break; case 0x7e: // Deco, ASC sample.event.type = SAMPLE_EVENT_DECOSTOP; break; case 0x7f: // Ceiling, ERR sample.event.type = SAMPLE_EVENT_CEILING; break; case 0x81: // Slow sample.event.type = SAMPLE_EVENT_ASCENT; break; default: // Unknown WARNING (abstract->context, "Unknown event"); break; } if (sample.event.type != SAMPLE_EVENT_NONE) { if (callback) callback (DC_SAMPLE_EVENT, sample, userdata); } } } // Time if (complete) { time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); } // Depth (0 ft) sample.depth = 0; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/suunto_eon_parser.c
/* * libdivecomputer * * Copyright (C) 2008 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <stdlib.h> #include <string.h> // memcmp #include <libdivecomputer/units.h> #include "reefnet_sensusultra.h" #include "context-private.h" #include "parser-private.h" #include "array.h" #define ISINSTANCE(parser) dc_parser_isinstance((parser), &reefnet_sensusultra_parser_vtable) typedef struct reefnet_sensusultra_parser_t reefnet_sensusultra_parser_t; struct reefnet_sensusultra_parser_t { dc_parser_t base; // Depth calibration. double atmospheric; double hydrostatic; // Clock synchronization. unsigned int devtime; dc_ticks_t systime; // Cached fields. unsigned int cached; unsigned int divetime; unsigned int maxdepth; }; static dc_status_t reefnet_sensusultra_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size); static dc_status_t reefnet_sensusultra_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime); static dc_status_t reefnet_sensusultra_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value); static dc_status_t reefnet_sensusultra_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata); static const dc_parser_vtable_t reefnet_sensusultra_parser_vtable = { sizeof(reefnet_sensusultra_parser_t), DC_FAMILY_REEFNET_SENSUSULTRA, reefnet_sensusultra_parser_set_data, /* set_data */ reefnet_sensusultra_parser_get_datetime, /* datetime */ reefnet_sensusultra_parser_get_field, /* fields */ reefnet_sensusultra_parser_samples_foreach, /* samples_foreach */ NULL /* destroy */ }; dc_status_t reefnet_sensusultra_parser_create (dc_parser_t **out, dc_context_t *context, unsigned int devtime, dc_ticks_t systime) { reefnet_sensusultra_parser_t *parser = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. parser = (reefnet_sensusultra_parser_t *) dc_parser_allocate (context, &reefnet_sensusultra_parser_vtable); if (parser == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. parser->atmospheric = ATM; parser->hydrostatic = 1025.0 * GRAVITY; parser->devtime = devtime; parser->systime = systime; parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; *out = (dc_parser_t*) parser; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_parser_set_data (dc_parser_t *abstract, const unsigned char *data, unsigned int size) { reefnet_sensusultra_parser_t *parser = (reefnet_sensusultra_parser_t*) abstract; // Reset the cache. parser->cached = 0; parser->divetime = 0; parser->maxdepth = 0; return DC_STATUS_SUCCESS; } dc_status_t reefnet_sensusultra_parser_set_calibration (dc_parser_t *abstract, double atmospheric, double hydrostatic) { reefnet_sensusultra_parser_t *parser = (reefnet_sensusultra_parser_t*) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; parser->atmospheric = atmospheric; parser->hydrostatic = hydrostatic; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_parser_get_datetime (dc_parser_t *abstract, dc_datetime_t *datetime) { reefnet_sensusultra_parser_t *parser = (reefnet_sensusultra_parser_t *) abstract; if (abstract->size < 4 + 4) return DC_STATUS_DATAFORMAT; unsigned int timestamp = array_uint32_le (abstract->data + 4); dc_ticks_t ticks = parser->systime - (parser->devtime - timestamp); if (!dc_datetime_localtime (datetime, ticks)) return DC_STATUS_DATAFORMAT; return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_parser_get_field (dc_parser_t *abstract, dc_field_type_t type, unsigned int flags, void *value) { reefnet_sensusultra_parser_t *parser = (reefnet_sensusultra_parser_t *) abstract; if (abstract->size < 20) return DC_STATUS_DATAFORMAT; if (!parser->cached) { const unsigned char footer[4] = {0xFF, 0xFF, 0xFF, 0xFF}; const unsigned char *data = abstract->data; unsigned int size = abstract->size; unsigned int interval = array_uint16_le (data + 8); unsigned int threshold = array_uint16_le (data + 10); unsigned int maxdepth = 0; unsigned int nsamples = 0; unsigned int offset = 16; while (offset + sizeof (footer) <= size && memcmp (data + offset, footer, sizeof (footer)) != 0) { unsigned int depth = array_uint16_le (data + offset + 2); if (depth >= threshold) { if (depth > maxdepth) maxdepth = depth; nsamples++; } offset += 4; } parser->cached = 1; parser->divetime = nsamples * interval; parser->maxdepth = maxdepth; } if (value) { switch (type) { case DC_FIELD_DIVETIME: *((unsigned int *) value) = parser->divetime; break; case DC_FIELD_MAXDEPTH: *((double *) value) = (parser->maxdepth * BAR / 1000.0 - parser->atmospheric) / parser->hydrostatic; break; case DC_FIELD_GASMIX_COUNT: *((unsigned int *) value) = 0; break; case DC_FIELD_DIVEMODE: *((dc_divemode_t *) value) = DC_DIVEMODE_GAUGE; break; default: return DC_STATUS_UNSUPPORTED; } } return DC_STATUS_SUCCESS; } static dc_status_t reefnet_sensusultra_parser_samples_foreach (dc_parser_t *abstract, dc_sample_callback_t callback, void *userdata) { reefnet_sensusultra_parser_t *parser = (reefnet_sensusultra_parser_t*) abstract; const unsigned char header[4] = {0x00, 0x00, 0x00, 0x00}; const unsigned char footer[4] = {0xFF, 0xFF, 0xFF, 0xFF}; const unsigned char *data = abstract->data; unsigned int size = abstract->size; unsigned int offset = 0; while (offset + sizeof (header) <= size) { if (memcmp (data + offset, header, sizeof (header)) == 0) { if (offset + 16 > size) return DC_STATUS_DATAFORMAT; unsigned int time = 0; unsigned int interval = array_uint16_le (data + offset + 8); offset += 16; while (offset + sizeof (footer) <= size && memcmp (data + offset, footer, sizeof (footer)) != 0) { dc_sample_value_t sample = {0}; // Time (seconds) time += interval; sample.time = time; if (callback) callback (DC_SAMPLE_TIME, sample, userdata); // Temperature (0.01 °K) unsigned int temperature = array_uint16_le (data + offset); sample.temperature = temperature / 100.0 - 273.15; if (callback) callback (DC_SAMPLE_TEMPERATURE, sample, userdata); // Depth (absolute pressure in millibar) unsigned int depth = array_uint16_le (data + offset + 2); sample.depth = (depth * BAR / 1000.0 - parser->atmospheric) / parser->hydrostatic; if (callback) callback (DC_SAMPLE_DEPTH, sample, userdata); offset += 4; } break; } else { offset++; } } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/reefnet_sensusultra_parser.c
/* * libdivecomputer * * Copyright (C) 2013 Jef Driesen * Copyright (C) 2014 Anton Lundin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #include <stdio.h> // FILE, fopen #include "hw_ostc3.h" #include "context-private.h" #include "device-private.h" #include "serial.h" #include "array.h" #include "aes.h" #include "platform.h" #define ISINSTANCE(device) dc_device_isinstance((device), &hw_ostc3_device_vtable) #define SZ_DISPLAY 16 #define SZ_CUSTOMTEXT 60 #define SZ_VERSION (SZ_CUSTOMTEXT + 4) #define SZ_HARDWARE 1 #define SZ_HARDWARE2 5 #define SZ_MEMORY 0x400000 #define SZ_CONFIG 4 #define SZ_FWINFO 4 #define SZ_FIRMWARE 0x01E000 // 120KB #define SZ_FIRMWARE_BLOCK 0x1000 // 4KB #define FIRMWARE_AREA 0x3E0000 #define RB_LOGBOOK_SIZE_COMPACT 16 #define RB_LOGBOOK_SIZE_FULL 256 #define RB_LOGBOOK_COUNT 256 #define S_BLOCK_READ 0x20 #define S_BLOCK_WRITE 0x30 #define S_ERASE 0x42 #define S_READY 0x4C #define READY 0x4D #define S_UPGRADE 0x50 #define HARDWARE2 0x60 #define HEADER 0x61 #define CLOCK 0x62 #define CUSTOMTEXT 0x63 #define DIVE 0x66 #define IDENTITY 0x69 #define HARDWARE 0x6A #define S_FWINFO 0x6B #define DISPLAY 0x6E #define COMPACT 0x6D #define READ 0x72 #define S_UPLOAD 0x73 #define WRITE 0x77 #define RESET 0x78 #define INIT 0xBB #define EXIT 0xFF #define INVALID 0xFFFFFFFF #define UNKNOWN 0x00 #define OSTC3 0x0A #define OSTC4 0x3B #define SPORT 0x12 #define CR 0x05 #define NODELAY 0 typedef enum hw_ostc3_state_t { OPEN, DOWNLOAD, SERVICE, REBOOTING, } hw_ostc3_state_t; typedef struct hw_ostc3_device_t { dc_device_t base; dc_iostream_t *iostream; unsigned int hardware; unsigned int feature; unsigned int model; unsigned char fingerprint[5]; hw_ostc3_state_t state; } hw_ostc3_device_t; typedef struct hw_ostc3_logbook_t { unsigned int size; unsigned int profile; unsigned int fingerprint; unsigned int number; } hw_ostc3_logbook_t; typedef struct hw_ostc3_firmware_t { unsigned char data[SZ_FIRMWARE]; unsigned int checksum; } hw_ostc3_firmware_t; // This key is used both for the Ostc3 and its cousin, // the Ostc Sport. // The Frog uses a similar protocol, and with another key. static const unsigned char ostc3_key[16] = { 0xF1, 0xE9, 0xB0, 0x30, 0x45, 0x6F, 0xBE, 0x55, 0xFF, 0xE7, 0xF8, 0x31, 0x13, 0x6C, 0xF2, 0xFE }; static dc_status_t hw_ostc3_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t hw_ostc3_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size); static dc_status_t hw_ostc3_device_write (dc_device_t *abstract, unsigned int address, const unsigned char data[], unsigned int size); static dc_status_t hw_ostc3_device_dump (dc_device_t *abstract, dc_buffer_t *buffer); static dc_status_t hw_ostc3_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t hw_ostc3_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime); static dc_status_t hw_ostc3_device_close (dc_device_t *abstract); static const dc_device_vtable_t hw_ostc3_device_vtable = { sizeof(hw_ostc3_device_t), DC_FAMILY_HW_OSTC3, hw_ostc3_device_set_fingerprint, /* set_fingerprint */ hw_ostc3_device_read, /* read */ hw_ostc3_device_write, /* write */ hw_ostc3_device_dump, /* dump */ hw_ostc3_device_foreach, /* foreach */ hw_ostc3_device_timesync, /* timesync */ hw_ostc3_device_close /* close */ }; static const hw_ostc3_logbook_t hw_ostc3_logbook_compact = { RB_LOGBOOK_SIZE_COMPACT, /* size */ 0, /* profile */ 3, /* fingerprint */ 13, /* number */ }; static const hw_ostc3_logbook_t hw_ostc3_logbook_full = { RB_LOGBOOK_SIZE_FULL, /* size */ 9, /* profile */ 12, /* fingerprint */ 80, /* number */ }; static int hw_ostc3_strncpy (unsigned char *data, unsigned int size, const char *text) { // Check the maximum length. size_t length = (text ? strlen (text) : 0); if (length > size) { return -1; } // Copy the text. if (length) memcpy (data, text, length); // Pad with spaces. memset (data + length, 0x20, size - length); return 0; } static dc_status_t hw_ostc3_transfer (hw_ostc3_device_t *device, dc_event_progress_t *progress, unsigned char cmd, const unsigned char input[], unsigned int isize, unsigned char output[], unsigned int osize, unsigned int delay) { dc_device_t *abstract = (dc_device_t *) device; dc_status_t status = DC_STATUS_SUCCESS; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Get the correct ready byte for the current state. const unsigned char ready = (device->state == SERVICE ? S_READY : READY); // Send the command. unsigned char command[1] = {cmd}; status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return status; } // Read the echo. unsigned char echo[1] = {0}; status = dc_iostream_read (device->iostream, echo, sizeof (echo), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the echo."); return status; } // Verify the echo. if (memcmp (echo, command, sizeof (command)) != 0) { if (echo[0] == ready) { ERROR (abstract->context, "Unsupported command."); return DC_STATUS_UNSUPPORTED; } else { ERROR (abstract->context, "Unexpected echo."); return DC_STATUS_PROTOCOL; } } if (input) { // Send the input data packet. unsigned int nbytes = 0; while (nbytes < isize) { // Set the minimum packet size. unsigned int len = 64; // Limit the packet size to the total size. if (nbytes + len > isize) len = isize - nbytes; // Write the packet. status = dc_iostream_write (device->iostream, input + nbytes, len, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the data packet."); return status; } // Update and emit a progress event. if (progress) { progress->current += len; device_event_emit ((dc_device_t *) device, DC_EVENT_PROGRESS, progress); } nbytes += len; } } if (output) { unsigned int nbytes = 0; while (nbytes < osize) { // Set the minimum packet size. unsigned int len = 1024; // Increase the packet size if more data is immediately available. size_t available = 0; status = dc_iostream_get_available (device->iostream, &available); if (status == DC_STATUS_SUCCESS && available > len) len = available; // Limit the packet size to the total size. if (nbytes + len > osize) len = osize - nbytes; // Read the packet. status = dc_iostream_read (device->iostream, output + nbytes, len, NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the answer."); return status; } // Update and emit a progress event. if (progress) { progress->current += len; device_event_emit ((dc_device_t *) device, DC_EVENT_PROGRESS, progress); } nbytes += len; } } if (delay) { unsigned int count = delay / 100; for (unsigned int i = 0; i < count; ++i) { size_t available = 0; status = dc_iostream_get_available (device->iostream, &available); if (status == DC_STATUS_SUCCESS && available > 0) break; dc_iostream_sleep (device->iostream, 100); } } if (cmd != EXIT) { // Read the ready byte. unsigned char answer[1] = {0}; status = dc_iostream_read (device->iostream, answer, sizeof (answer), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to receive the ready byte."); return status; } // Verify the ready byte. if (answer[0] != ready) { ERROR (abstract->context, "Unexpected ready byte."); return DC_STATUS_PROTOCOL; } } return DC_STATUS_SUCCESS; } dc_status_t hw_ostc3_device_open (dc_device_t **out, dc_context_t *context, const char *name) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc3_device_t *device = NULL; if (out == NULL) return DC_STATUS_INVALIDARGS; // Allocate memory. device = (hw_ostc3_device_t *) dc_device_allocate (context, &hw_ostc3_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->iostream = NULL; device->hardware = INVALID; device->feature = 0; device->model = 0; memset (device->fingerprint, 0, sizeof (device->fingerprint)); // Open the device. status = dc_serial_open (&device->iostream, context, name); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to open the serial port."); goto error_free; } // Set the serial communication protocol (115200 8N1). status = dc_iostream_configure (device->iostream, 115200, 8, DC_PARITY_NONE, DC_STOPBITS_ONE, DC_FLOWCONTROL_NONE); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the terminal attributes."); goto error_close; } // Set the timeout for receiving data (3000ms). status = dc_iostream_set_timeout (device->iostream, 3000); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to set the timeout."); goto error_close; } // Make sure everything is in a sane state. dc_iostream_sleep (device->iostream, 300); dc_iostream_purge (device->iostream, DC_DIRECTION_ALL); device->state = OPEN; *out = (dc_device_t *) device; return DC_STATUS_SUCCESS; error_close: dc_iostream_close (device->iostream); error_free: dc_device_deallocate ((dc_device_t *) device); return status; } static dc_status_t hw_ostc3_device_id (hw_ostc3_device_t *device, unsigned char data[], unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; if (size != SZ_HARDWARE && size != SZ_HARDWARE2) return DC_STATUS_INVALIDARGS; // Send the command. unsigned char hardware[SZ_HARDWARE2] = {0}; status = hw_ostc3_transfer (device, NULL, HARDWARE2, NULL, 0, hardware, SZ_HARDWARE2, NODELAY); if (status == DC_STATUS_UNSUPPORTED) { status = hw_ostc3_transfer (device, NULL, HARDWARE, NULL, 0, hardware + 1, SZ_HARDWARE, NODELAY); } if (status != DC_STATUS_SUCCESS) return status; if (size == SZ_HARDWARE2) { memcpy (data, hardware, SZ_HARDWARE2); } else { memcpy (data, hardware + 1, SZ_HARDWARE); } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_device_init_download (hw_ostc3_device_t *device) { dc_device_t *abstract = (dc_device_t *) device; dc_context_t *context = (abstract ? abstract->context : NULL); // Send the init command. dc_status_t status = hw_ostc3_transfer (device, NULL, INIT, NULL, 0, NULL, 0, NODELAY); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to send the command."); return status; } device->state = DOWNLOAD; return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_device_init_service (hw_ostc3_device_t *device) { dc_status_t status = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; dc_context_t *context = (abstract ? abstract->context : NULL); unsigned char command[] = {0xAA, 0xAB, 0xCD, 0xEF}; unsigned char output[5]; // We cant use hw_ostc3_transfer here, due to the different echos status = dc_iostream_write (device->iostream, command, sizeof (command), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to send the command."); return status; } // Give the device some time to enter service mode dc_iostream_sleep (device->iostream, 100); // Read the response status = dc_iostream_read (device->iostream, output, sizeof (output), NULL); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to receive the echo."); return status; } // Verify the response to service mode if (output[0] != 0x4B || output[1] != 0xAB || output[2] != 0xCD || output[3] != 0xEF || output[4] != S_READY) { ERROR (context, "Failed to verify echo."); return DC_STATUS_PROTOCOL; } device->state = SERVICE; return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_device_init (hw_ostc3_device_t *device, hw_ostc3_state_t state) { dc_status_t rc = DC_STATUS_SUCCESS; dc_device_t *abstract = (dc_device_t *) device; if (device->state == state) { // No change. rc = DC_STATUS_SUCCESS; } else if (device->state == OPEN) { // Change to download or service mode. if (state == DOWNLOAD) { rc = hw_ostc3_device_init_download(device); } else if (state == SERVICE) { rc = hw_ostc3_device_init_service(device); } else { rc = DC_STATUS_INVALIDARGS; } } else if (device->state == SERVICE && state == DOWNLOAD) { // Switching between service and download mode is not possible. // But in service mode, all download commands are supported too, // so there is no need to change the state. rc = DC_STATUS_SUCCESS; } else { // Not supported. rc = DC_STATUS_INVALIDARGS; } if (rc != DC_STATUS_SUCCESS) return rc; if (device->hardware != INVALID) return DC_STATUS_SUCCESS; // Read the hardware descriptor. unsigned char hardware[SZ_HARDWARE2] = {0, UNKNOWN}; rc = hw_ostc3_device_id (device, hardware, sizeof(hardware)); if (rc != DC_STATUS_SUCCESS && rc != DC_STATUS_UNSUPPORTED) { ERROR (abstract->context, "Failed to read the hardware descriptor."); return rc; } // Cache the descriptor. device->hardware = array_uint16_be(hardware + 0); device->feature = array_uint16_be(hardware + 2); device->model = hardware[4]; return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_device_close (dc_device_t *abstract) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc3_device_t *device = (hw_ostc3_device_t*) abstract; dc_status_t rc = DC_STATUS_SUCCESS; // Send the exit command if (device->state == DOWNLOAD || device->state == SERVICE) { rc = hw_ostc3_transfer (device, NULL, EXIT, NULL, 0, NULL, 0, NODELAY); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); dc_status_set_error(&status, rc); } } // Close the device. rc = dc_iostream_close (device->iostream); if (rc != DC_STATUS_SUCCESS) { dc_status_set_error(&status, rc); } return status; } static dc_status_t hw_ostc3_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } dc_status_t hw_ostc3_device_version (dc_device_t *abstract, unsigned char data[], unsigned int size) { hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size != SZ_VERSION) return DC_STATUS_INVALIDARGS; dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD); if (rc != DC_STATUS_SUCCESS) return rc; // Send the command. rc = hw_ostc3_transfer (device, NULL, IDENTITY, NULL, 0, data, size, NODELAY); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t hw_ostc3_device_hardware (dc_device_t *abstract, unsigned char data[], unsigned int size) { hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size != SZ_HARDWARE && size != SZ_HARDWARE2) return DC_STATUS_INVALIDARGS; dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD); if (rc != DC_STATUS_SUCCESS) return rc; // Send the command. rc = hw_ostc3_device_id (device, data, size); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_MEMORY; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD); if (rc != DC_STATUS_SUCCESS) return rc; // Download the version data. unsigned char id[SZ_VERSION] = {0}; rc = hw_ostc3_device_version (abstract, id, sizeof (id)); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the version."); return rc; } // Emit a device info event. dc_event_devinfo_t devinfo; if (device->hardware == OSTC4) { devinfo.firmware = array_uint16_le (id + 2); } else { devinfo.firmware = array_uint16_be (id + 2); } devinfo.serial = array_uint16_le (id + 0); if (device->hardware != UNKNOWN) { devinfo.model = device->hardware; } else { // Fallback to the serial number. if (devinfo.serial > 10000) devinfo.model = SPORT; else devinfo.model = OSTC3; } device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); // Allocate memory. unsigned char *header = (unsigned char *) malloc (RB_LOGBOOK_SIZE_FULL * RB_LOGBOOK_COUNT); if (header == NULL) { ERROR (abstract->context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Download the compact logbook headers. If the firmware doesn't support // compact headers yet, fallback to downloading the full logbook headers. // This is slower, but also works for older firmware versions. unsigned int compact = 1; rc = hw_ostc3_transfer (device, &progress, COMPACT, NULL, 0, header, RB_LOGBOOK_SIZE_COMPACT * RB_LOGBOOK_COUNT, NODELAY); if (rc == DC_STATUS_UNSUPPORTED) { compact = 0; rc = hw_ostc3_transfer (device, &progress, HEADER, NULL, 0, header, RB_LOGBOOK_SIZE_FULL * RB_LOGBOOK_COUNT, NODELAY); } if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the header."); free (header); return rc; } // Get the correct logbook layout. const hw_ostc3_logbook_t *logbook = NULL; if (compact) { logbook = &hw_ostc3_logbook_compact; } else { logbook = &hw_ostc3_logbook_full; } // Locate the most recent dive. // The device maintains an internal counter which is incremented for every // dive, and the current value at the time of the dive is stored in the // dive header. Thus the most recent dive will have the highest value. unsigned int count = 0; unsigned int latest = 0; unsigned int maximum = 0; for (unsigned int i = 0; i < RB_LOGBOOK_COUNT; ++i) { unsigned int offset = i * logbook->size; // Ignore uninitialized header entries. if (array_isequal (header + offset, logbook->size, 0xFF)) continue; // Get the internal dive number. unsigned int current = array_uint16_le (header + offset + logbook->number); if (current > maximum) { maximum = current; latest = i; } count++; } // Calculate the total and maximum size. unsigned int ndives = 0; unsigned int size = 0; unsigned int maxsize = 0; for (unsigned int i = 0; i < count; ++i) { unsigned int idx = (latest + RB_LOGBOOK_COUNT - i) % RB_LOGBOOK_COUNT; unsigned int offset = idx * logbook->size; // Uninitialized header entries should no longer be present at this // stage, unless the dives are interleaved with empty entries. But // that's something we don't support at all. if (array_isequal (header + offset, logbook->size, 0xFF)) { WARNING (abstract->context, "Unexpected empty header found."); break; } // Calculate the profile length. unsigned int length = RB_LOGBOOK_SIZE_FULL + array_uint24_le (header + offset + logbook->profile) - 3; if (!compact) { // Workaround for a bug in older firmware versions. unsigned int firmware = array_uint16_be (header + offset + 0x30); if (firmware < 93) length -= 3; } if (length < RB_LOGBOOK_SIZE_FULL) { ERROR (abstract->context, "Invalid profile length (%u bytes).", length); free (header); return DC_STATUS_DATAFORMAT; } // Check the fingerprint data. if (memcmp (header + offset + logbook->fingerprint, device->fingerprint, sizeof (device->fingerprint)) == 0) break; if (length > maxsize) maxsize = length; size += length; ndives++; } // Update and emit a progress event. progress.maximum = (logbook->size * RB_LOGBOOK_COUNT) + size + ndives; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Finish immediately if there are no dives available. if (ndives == 0) { free (header); return DC_STATUS_SUCCESS; } // Allocate enough memory for the largest dive. unsigned char *profile = (unsigned char *) malloc (maxsize); if (profile == NULL) { ERROR (abstract->context, "Failed to allocate memory."); free (header); return DC_STATUS_NOMEMORY; } // Download the dives. for (unsigned int i = 0; i < ndives; ++i) { unsigned int idx = (latest + RB_LOGBOOK_COUNT - i) % RB_LOGBOOK_COUNT; unsigned int offset = idx * logbook->size; // Calculate the profile length. unsigned int length = RB_LOGBOOK_SIZE_FULL + array_uint24_le (header + offset + logbook->profile) - 3; if (!compact) { // Workaround for a bug in older firmware versions. unsigned int firmware = array_uint16_be (header + offset + 0x30); if (firmware < 93) length -= 3; } // Download the dive. unsigned char number[1] = {idx}; rc = hw_ostc3_transfer (device, &progress, DIVE, number, sizeof (number), profile, length, NODELAY); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the dive."); free (profile); free (header); return rc; } // Verify the header in the logbook and profile are identical. if (!compact && memcmp (profile, header + offset, logbook->size) != 0) { ERROR (abstract->context, "Unexpected profile header."); free (profile); free (header); return rc; } // Detect invalid profile data. unsigned int delta = device->hardware == OSTC4 ? 3 : 0; if (length < RB_LOGBOOK_SIZE_FULL + 2 || profile[length - 2] != 0xFD || profile[length - 1] != 0xFD) { // A valid profile should have at least a correct 2 byte // end-of-profile marker. WARNING (abstract->context, "Invalid profile end marker detected!"); length = RB_LOGBOOK_SIZE_FULL; } else if (length == RB_LOGBOOK_SIZE_FULL + 2) { // A profile containing only the 2 byte end-of-profile // marker is considered a valid empty profile. } else if (length < RB_LOGBOOK_SIZE_FULL + 5 + 2 || array_uint24_le (profile + RB_LOGBOOK_SIZE_FULL) + delta != array_uint24_le (profile + 9)) { // If there is more data available, then there should be a // valid profile header containing a length matching the // length in the dive header. WARNING (abstract->context, "Invalid profile header detected."); length = RB_LOGBOOK_SIZE_FULL; } if (callback && !callback (profile, length, profile + 12, sizeof (device->fingerprint), userdata)) break; } free (profile); free (header); return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_device_timesync (dc_device_t *abstract, const dc_datetime_t *datetime) { hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if (datetime == NULL) { ERROR (abstract->context, "Invalid parameter specified."); return DC_STATUS_INVALIDARGS; } dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD); if (rc != DC_STATUS_SUCCESS) return rc; // Send the command. unsigned char packet[6] = { datetime->hour, datetime->minute, datetime->second, datetime->month, datetime->day, datetime->year - 2000}; rc = hw_ostc3_transfer (device, NULL, CLOCK, packet, sizeof (packet), NULL, 0, NODELAY); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t hw_ostc3_device_display (dc_device_t *abstract, const char *text) { hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Pad the data packet with spaces. unsigned char packet[SZ_DISPLAY] = {0}; if (hw_ostc3_strncpy (packet, sizeof (packet), text) != 0) { ERROR (abstract->context, "Invalid parameter specified."); return DC_STATUS_INVALIDARGS; } dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD); if (rc != DC_STATUS_SUCCESS) return rc; // Send the command. rc = hw_ostc3_transfer (device, NULL, DISPLAY, packet, sizeof (packet), NULL, 0, NODELAY); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t hw_ostc3_device_customtext (dc_device_t *abstract, const char *text) { hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Pad the data packet with spaces. unsigned char packet[SZ_CUSTOMTEXT] = {0}; if (hw_ostc3_strncpy (packet, sizeof (packet), text) != 0) { ERROR (abstract->context, "Invalid parameter specified."); return DC_STATUS_INVALIDARGS; } dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD); if (rc != DC_STATUS_SUCCESS) return rc; // Send the command. rc = hw_ostc3_transfer (device, NULL, CUSTOMTEXT, packet, sizeof (packet), NULL, 0, NODELAY); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t hw_ostc3_device_config_read (dc_device_t *abstract, unsigned int config, unsigned char data[], unsigned int size) { hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD); if (rc != DC_STATUS_SUCCESS) return rc; if (device->hardware == OSTC4 ? size != SZ_CONFIG : size > SZ_CONFIG) { ERROR (abstract->context, "Invalid parameter specified."); return DC_STATUS_INVALIDARGS; } // Send the command. unsigned char command[1] = {config}; rc = hw_ostc3_transfer (device, NULL, READ, command, sizeof (command), data, size, NODELAY); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t hw_ostc3_device_config_write (dc_device_t *abstract, unsigned int config, const unsigned char data[], unsigned int size) { hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD); if (rc != DC_STATUS_SUCCESS) return rc; if (device->hardware == OSTC4 ? size != SZ_CONFIG : size > SZ_CONFIG) { ERROR (abstract->context, "Invalid parameter specified."); return DC_STATUS_INVALIDARGS; } // Send the command. unsigned char command[SZ_CONFIG + 1] = {config}; memcpy(command + 1, data, size); rc = hw_ostc3_transfer (device, NULL, WRITE, command, size + 1, NULL, 0, NODELAY); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } dc_status_t hw_ostc3_device_config_reset (dc_device_t *abstract) { hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; dc_status_t rc = hw_ostc3_device_init (device, DOWNLOAD); if (rc != DC_STATUS_SUCCESS) return rc; // Send the command. rc = hw_ostc3_transfer (device, NULL, RESET, NULL, 0, NULL, 0, NODELAY); if (rc != DC_STATUS_SUCCESS) return rc; return DC_STATUS_SUCCESS; } // This is a variant of fletcher16 with a 16 bit sum instead of an 8 bit sum, // and modulo 2^16 instead of 2^16-1 static unsigned int hw_ostc3_firmware_checksum (const unsigned char data[], unsigned int size) { unsigned short low = 0; unsigned short high = 0; for (unsigned int i = 0; i < size; i++) { low += data[i]; high += low; } return (((unsigned int)high) << 16) + low; } static dc_status_t hw_ostc3_firmware_readline (FILE *fp, dc_context_t *context, unsigned int addr, unsigned char data[], unsigned int size) { unsigned char ascii[39]; unsigned char faddr_byte[3]; unsigned int faddr = 0; int n = 0; if (size > 16) { ERROR (context, "Invalid arguments."); return DC_STATUS_INVALIDARGS; } // Read the start code. while (1) { n = fread (ascii, 1, 1, fp); if (n != 1) { ERROR (context, "Failed to read the start code."); return DC_STATUS_IO; } if (ascii[0] == ':') break; // Ignore CR and LF characters. if (ascii[0] != '\n' && ascii[0] != '\r') { ERROR (context, "Unexpected character (0x%02x).", ascii[0]); return DC_STATUS_DATAFORMAT; } } // Read the payload. n = fread (ascii + 1, 1, 6 + size * 2, fp); if (n != 6 + size * 2) { ERROR (context, "Failed to read the data."); return DC_STATUS_IO; } // Convert the address to binary representation. if (array_convert_hex2bin(ascii + 1, 6, faddr_byte, sizeof(faddr_byte)) != 0) { ERROR (context, "Invalid hexadecimal character."); return DC_STATUS_DATAFORMAT; } // Get the address. faddr = array_uint24_be (faddr_byte); if (faddr != addr) { ERROR (context, "Unexpected address (0x%06x, 0x%06x).", faddr, addr); return DC_STATUS_DATAFORMAT; } // Convert the payload to binary representation. if (array_convert_hex2bin (ascii + 1 + 6, size * 2, data, size) != 0) { ERROR (context, "Invalid hexadecimal character."); return DC_STATUS_DATAFORMAT; } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_firmware_readfile3 (hw_ostc3_firmware_t *firmware, dc_context_t *context, const char *filename) { dc_status_t rc = DC_STATUS_SUCCESS; FILE *fp = NULL; unsigned char iv[16] = {0}; unsigned char tmpbuf[16] = {0}; unsigned char encrypted[16] = {0}; unsigned int bytes = 0, addr = 0; unsigned char checksum[4]; if (firmware == NULL) { ERROR (context, "Invalid arguments."); return DC_STATUS_INVALIDARGS; } // Initialize the buffers. memset (firmware->data, 0xFF, sizeof (firmware->data)); firmware->checksum = 0; fp = fopen (filename, "rb"); if (fp == NULL) { ERROR (context, "Failed to open the file."); return DC_STATUS_IO; } rc = hw_ostc3_firmware_readline (fp, context, 0, iv, sizeof(iv)); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to parse header."); fclose (fp); return rc; } bytes += 16; // Load the iv for AES-FCB-mode AES128_ECB_encrypt (iv, ostc3_key, tmpbuf); for (addr = 0; addr < SZ_FIRMWARE; addr += 16, bytes += 16) { rc = hw_ostc3_firmware_readline (fp, context, bytes, encrypted, sizeof(encrypted)); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to parse file data."); fclose (fp); return rc; } // Decrypt AES-FCB data for (unsigned int i = 0; i < 16; i++) firmware->data[addr + i] = encrypted[i] ^ tmpbuf[i]; // Run the next round of encryption AES128_ECB_encrypt (encrypted, ostc3_key, tmpbuf); } // This file format contains a tail with the checksum in rc = hw_ostc3_firmware_readline (fp, context, bytes, checksum, sizeof(checksum)); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to parse file tail."); fclose (fp); return rc; } fclose (fp); unsigned int csum1 = array_uint32_le (checksum); unsigned int csum2 = hw_ostc3_firmware_checksum (firmware->data, sizeof(firmware->data)); if (csum1 != csum2) { ERROR (context, "Failed to verify file checksum."); return DC_STATUS_DATAFORMAT; } firmware->checksum = csum1; return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_firmware_readfile4 (dc_buffer_t *buffer, dc_context_t *context, const char *filename) { FILE *fp = NULL; if (buffer == NULL) { ERROR (context, "Invalid arguments."); return DC_STATUS_INVALIDARGS; } // Open the file. fp = fopen (filename, "rb"); if (fp == NULL) { ERROR (context, "Failed to open the file."); return DC_STATUS_IO; } // Read the entire file into the buffer. size_t n = 0; unsigned char block[1024] = {0}; while ((n = fread (block, 1, sizeof (block), fp)) > 0) { if (!dc_buffer_append (buffer, block, n)) { ERROR (context, "Insufficient buffer space available."); fclose (fp); return DC_STATUS_NOMEMORY; } } // Close the file. fclose (fp); // Verify the minimum size. size_t size = dc_buffer_get_size (buffer); if (size < 4) { ERROR (context, "Invalid file size."); return DC_STATUS_DATAFORMAT; } // Verify the checksum. const unsigned char *data = dc_buffer_get_data (buffer); unsigned int csum1 = array_uint32_le (data + size - 4); unsigned int csum2 = hw_ostc3_firmware_checksum (data, size - 4); if (csum1 != csum2) { ERROR (context, "Failed to verify file checksum."); return DC_STATUS_DATAFORMAT; } // Remove the checksum. dc_buffer_slice (buffer, 0, size - 4); return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_firmware_erase (hw_ostc3_device_t *device, unsigned int addr, unsigned int size) { // Convert size to number of pages, rounded up. unsigned char blocks = ((size + SZ_FIRMWARE_BLOCK - 1) / SZ_FIRMWARE_BLOCK); // Erase just the needed pages. unsigned char buffer[4]; array_uint24_be_set (buffer, addr); buffer[3] = blocks; return hw_ostc3_transfer (device, NULL, S_ERASE, buffer, sizeof (buffer), NULL, 0, NODELAY); } static dc_status_t hw_ostc3_firmware_block_read (hw_ostc3_device_t *device, unsigned int addr, unsigned char block[], unsigned int block_size) { unsigned char buffer[6]; array_uint24_be_set (buffer, addr); array_uint24_be_set (buffer + 3, block_size); return hw_ostc3_transfer (device, NULL, S_BLOCK_READ, buffer, sizeof (buffer), block, block_size, NODELAY); } static dc_status_t hw_ostc3_firmware_block_write (hw_ostc3_device_t *device, unsigned int addr, const unsigned char block[], unsigned int block_size) { unsigned char buffer[3 + SZ_FIRMWARE_BLOCK]; // We currenty only support writing max SZ_FIRMWARE_BLOCK sized blocks. if (block_size > SZ_FIRMWARE_BLOCK) return DC_STATUS_INVALIDARGS; array_uint24_be_set (buffer, addr); memcpy (buffer + 3, block, block_size); return hw_ostc3_transfer (device, NULL, S_BLOCK_WRITE, buffer, 3 + block_size, NULL, 0, NODELAY); } static dc_status_t hw_ostc3_firmware_upgrade (dc_device_t *abstract, unsigned int checksum) { dc_status_t rc = DC_STATUS_SUCCESS; hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; dc_context_t *context = (abstract ? abstract->context : NULL); unsigned char buffer[5]; array_uint32_le_set (buffer, checksum); // Compute a one byte checksum, so the device can validate the firmware image. buffer[4] = 0x55; for (unsigned int i = 0; i < 4; i++) { buffer[4] ^= buffer[i]; buffer[4] = (buffer[4]<<1 | buffer[4]>>7); } rc = hw_ostc3_transfer (device, NULL, S_UPGRADE, buffer, sizeof (buffer), NULL, 0, NODELAY); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to send flash firmware command"); return rc; } // Now the device resets, and if everything is well, it reprograms. device->state = REBOOTING; return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_device_fwupdate3 (dc_device_t *abstract, const char *filename) { dc_status_t rc = DC_STATUS_SUCCESS; hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; dc_context_t *context = (abstract ? abstract->context : NULL); // Enable progress notifications. // load, erase, upload FZ, verify FZ, reprogram dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = 3 + SZ_FIRMWARE * 2 / SZ_FIRMWARE_BLOCK; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Allocate memory for the firmware data. hw_ostc3_firmware_t *firmware = (hw_ostc3_firmware_t *) malloc (sizeof (hw_ostc3_firmware_t)); if (firmware == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Read the hex file. rc = hw_ostc3_firmware_readfile3 (firmware, context, filename); if (rc != DC_STATUS_SUCCESS) { free (firmware); return rc; } // Device open and firmware loaded progress.current++; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); hw_ostc3_device_display (abstract, " Erasing FW..."); rc = hw_ostc3_firmware_erase (device, FIRMWARE_AREA, SZ_FIRMWARE); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to erase old firmware"); free (firmware); return rc; } // Memory erased progress.current++; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); hw_ostc3_device_display (abstract, " Uploading..."); for (unsigned int len = 0; len < SZ_FIRMWARE; len += SZ_FIRMWARE_BLOCK) { char status[SZ_DISPLAY + 1]; // Status message on the display snprintf (status, sizeof(status), " Uploading %2d%%", (100 * len) / SZ_FIRMWARE); hw_ostc3_device_display (abstract, status); rc = hw_ostc3_firmware_block_write (device, FIRMWARE_AREA + len, firmware->data + len, SZ_FIRMWARE_BLOCK); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to write block to device"); free(firmware); return rc; } // One block uploaded progress.current++; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); } hw_ostc3_device_display (abstract, " Verifying..."); for (unsigned int len = 0; len < SZ_FIRMWARE; len += SZ_FIRMWARE_BLOCK) { unsigned char block[SZ_FIRMWARE_BLOCK]; char status[SZ_DISPLAY + 1]; // Status message on the display snprintf (status, sizeof(status), " Verifying %2d%%", (100 * len) / SZ_FIRMWARE); hw_ostc3_device_display (abstract, status); rc = hw_ostc3_firmware_block_read (device, FIRMWARE_AREA + len, block, sizeof (block)); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to read block."); free (firmware); return rc; } if (memcmp (firmware->data + len, block, sizeof (block)) != 0) { ERROR (context, "Failed verify."); hw_ostc3_device_display (abstract, " Verify FAILED"); free (firmware); return DC_STATUS_PROTOCOL; } // One block verified progress.current++; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); } hw_ostc3_device_display (abstract, " Programming..."); rc = hw_ostc3_firmware_upgrade (abstract, firmware->checksum); if (rc != DC_STATUS_SUCCESS) { ERROR (context, "Failed to start programing"); free (firmware); return rc; } // Programing done! progress.current++; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); free (firmware); // Finished! return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_device_fwupdate4 (dc_device_t *abstract, const char *filename) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; dc_context_t *context = (abstract ? abstract->context : NULL); // Allocate memory for the firmware data. dc_buffer_t *buffer = dc_buffer_new (0); if (buffer == NULL) { ERROR (context, "Failed to allocate memory."); status = DC_STATUS_NOMEMORY; goto error; } // Read the firmware file. status = hw_ostc3_firmware_readfile4 (buffer, context, filename); if (status != DC_STATUS_SUCCESS) { goto error; } // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = dc_buffer_get_size (buffer); device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Cache the pointer and size. const unsigned char *data = dc_buffer_get_data (buffer); unsigned int size = dc_buffer_get_size (buffer); unsigned int offset = 0; while (offset + 4 <= size) { // Get the length of the firmware blob. unsigned int length = array_uint32_be(data + offset) + 20; if (offset + length > size) { status = DC_STATUS_DATAFORMAT; goto error; } // Get the blob type. unsigned char type = data[offset + 4]; // Estimate the required delay. // After uploading the firmware blob, the device writes the data // to flash memory. Since this takes a significant amount of // time, the ready byte is delayed. Therefore, the standard // timeout is no longer sufficient. The delays are estimated // based on actual measurements of the delay per byte. unsigned int usecs = length; if (type == 0xFF) { // Firmware usecs *= 50; } else if (type == 0xFE) { // RTE usecs *= 500; } else { // Fonts usecs *= 25; } // Read the firmware version info. unsigned char fwinfo[SZ_FWINFO] = {0}; status = hw_ostc3_transfer (device, NULL, S_FWINFO, data + offset + 4, 1, fwinfo, sizeof(fwinfo), NODELAY); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read the firmware info."); goto error; } // Upload the firmware blob. // The update is skipped if the two versions are already // identical, or if the blob is not present on the device. if (memcmp(data + offset + 12, fwinfo, sizeof(fwinfo)) != 0 && !array_isequal(fwinfo, sizeof(fwinfo), 0xFF)) { status = hw_ostc3_transfer (device, &progress, S_UPLOAD, data + offset, length, NULL, 0, usecs / 1000); if (status != DC_STATUS_SUCCESS) { goto error; } } else { // Update and emit a progress event. progress.current += length; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); } offset += length; } error: dc_buffer_free (buffer); return status; } dc_status_t hw_ostc3_device_fwupdate (dc_device_t *abstract, const char *filename) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; // Make sure the device is in service mode. status = hw_ostc3_device_init (device, SERVICE); if (status != DC_STATUS_SUCCESS) { return status; } if (device->hardware == OSTC4) { return hw_ostc3_device_fwupdate4 (abstract, filename); } else { return hw_ostc3_device_fwupdate3 (abstract, filename); } } static dc_status_t hw_ostc3_device_read (dc_device_t *abstract, unsigned int address, unsigned char data[], unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if ((address % SZ_FIRMWARE_BLOCK != 0) || (size % SZ_FIRMWARE_BLOCK != 0)) { ERROR (abstract->context, "Address or size not aligned to the page size!"); return DC_STATUS_INVALIDARGS; } // Make sure the device is in service mode. status = hw_ostc3_device_init (device, SERVICE); if (status != DC_STATUS_SUCCESS) { return status; } if (device->hardware == OSTC4) { return DC_STATUS_UNSUPPORTED; } unsigned int nbytes = 0; while (nbytes < size) { // Read a memory page. status = hw_ostc3_firmware_block_read (device, address + nbytes, data + nbytes, SZ_FIRMWARE_BLOCK); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read block."); return status; } nbytes += SZ_FIRMWARE_BLOCK; } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_device_write (dc_device_t *abstract, unsigned int address, const unsigned char data[], unsigned int size) { dc_status_t status = DC_STATUS_SUCCESS; hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; if ((address % SZ_FIRMWARE_BLOCK != 0) || (size % SZ_FIRMWARE_BLOCK != 0)) { ERROR (abstract->context, "Address or size not aligned to the page size!"); return DC_STATUS_INVALIDARGS; } // Make sure the device is in service mode. status = hw_ostc3_device_init (device, SERVICE); if (status != DC_STATUS_SUCCESS) { return status; } if (device->hardware == OSTC4) { return DC_STATUS_UNSUPPORTED; } // Erase the memory pages. status = hw_ostc3_firmware_erase (device, address, size); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to erase blocks."); return status; } unsigned int nbytes = 0; while (nbytes < size) { // Write a memory page. status = hw_ostc3_firmware_block_write (device, address + nbytes, data + nbytes, SZ_FIRMWARE_BLOCK); if (status != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to write block."); return status; } nbytes += SZ_FIRMWARE_BLOCK; } return DC_STATUS_SUCCESS; } static dc_status_t hw_ostc3_device_dump (dc_device_t *abstract, dc_buffer_t *buffer) { hw_ostc3_device_t *device = (hw_ostc3_device_t *) abstract; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_MEMORY; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Make sure the device is in service mode dc_status_t rc = hw_ostc3_device_init (device, SERVICE); if (rc != DC_STATUS_SUCCESS) { return rc; } // Allocate the required amount of memory. if (!dc_buffer_resize (buffer, SZ_MEMORY)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } unsigned char *data = dc_buffer_get_data (buffer); unsigned int nbytes = 0; while (nbytes < SZ_MEMORY) { // packet size. Can be almost arbetary size. unsigned int len = SZ_FIRMWARE_BLOCK; // Read a block rc = hw_ostc3_firmware_block_read (device, nbytes, data + nbytes, len); if (rc != DC_STATUS_SUCCESS) { ERROR (abstract->context, "Failed to read block."); return rc; } // Update and emit a progress event. progress.current += len; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); nbytes += len; } return DC_STATUS_SUCCESS; }
libdc-for-dirk-Subsurface-branch
src/hw_ostc3.c
/* * libdivecomputer * * Copyright (C) 2010 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <time.h> #include <libdivecomputer/datetime.h> static struct tm * dc_localtime_r (const time_t *t, struct tm *tm) { #ifdef HAVE_LOCALTIME_R return localtime_r (t, tm); #else struct tm *p = localtime (t); if (p == NULL) return NULL; if (tm) *tm = *p; return tm; #endif } static struct tm * dc_gmtime_r (const time_t *t, struct tm *tm) { #ifdef HAVE_GMTIME_R return gmtime_r (t, tm); #else struct tm *p = gmtime (t); if (p == NULL) return NULL; if (tm) *tm = *p; return tm; #endif } static time_t dc_timegm (struct tm *tm) { #if defined(HAVE_TIMEGM) return timegm (tm); #elif defined (HAVE__MKGMTIME) return _mkgmtime (tm); #else static const unsigned int mdays[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; if (tm == NULL || tm->tm_mon < 0 || tm->tm_mon > 11 || tm->tm_mday < 1 || tm->tm_mday > 31 || tm->tm_hour < 0 || tm->tm_hour > 23 || tm->tm_min < 0 || tm->tm_min > 59 || tm->tm_sec < 0 || tm->tm_sec > 60) return (time_t) -1; /* Number of leap days since 1970-01-01. */ int year = tm->tm_year + 1900 - (tm->tm_mon < 2); int leapdays = ((year / 4) - (year / 100) + (year / 400)) - ((1969 / 4) - (1969 / 100) + (1969 / 400)); time_t result = 0; result += (tm->tm_year - 70) * 365; result += leapdays; result += mdays[tm->tm_mon]; result += tm->tm_mday - 1; result *= 24; result += tm->tm_hour; result *= 60; result += tm->tm_min; result *= 60; result += tm->tm_sec; return result; #endif } dc_ticks_t dc_datetime_now (void) { return time (NULL); } dc_datetime_t * dc_datetime_localtime (dc_datetime_t *result, dc_ticks_t ticks) { time_t t = ticks; int offset = 0; struct tm tm; if (dc_localtime_r (&t, &tm) == NULL) return NULL; #ifdef HAVE_STRUCT_TM_TM_GMTOFF offset = tm.tm_gmtoff; #else struct tm tmp = tm; time_t t_local = dc_timegm (&tmp); if (t_local == (time_t) -1) return NULL; offset = t_local - t; #endif if (result) { result->year = tm.tm_year + 1900; result->month = tm.tm_mon + 1; result->day = tm.tm_mday; result->hour = tm.tm_hour; result->minute = tm.tm_min; result->second = tm.tm_sec; result->timezone = offset; } return result; } dc_datetime_t * dc_datetime_gmtime (dc_datetime_t *result, dc_ticks_t ticks) { time_t t = ticks; struct tm tm; if (dc_gmtime_r (&t, &tm) == NULL) return NULL; if (result) { result->year = tm.tm_year + 1900; result->month = tm.tm_mon + 1; result->day = tm.tm_mday; result->hour = tm.tm_hour; result->minute = tm.tm_min; result->second = tm.tm_sec; result->timezone = 0; } return result; } dc_ticks_t dc_datetime_mktime (const dc_datetime_t *dt) { if (dt == NULL) return -1; struct tm tm; tm.tm_year = dt->year - 1900; tm.tm_mon = dt->month - 1; tm.tm_mday = dt->day; tm.tm_hour = dt->hour; tm.tm_min = dt->minute; tm.tm_sec = dt->second; tm.tm_isdst = 0; time_t t = dc_timegm (&tm); if (t == (time_t) -1) return t; if (dt->timezone != DC_TIMEZONE_NONE) { t -= dt->timezone; } return t; }
libdc-for-dirk-Subsurface-branch
src/datetime.c
/* * libdivecomputer * * Copyright (C) 2011 Jef Driesen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <string.h> // memcmp, memcpy #include <stdlib.h> // malloc, free #ifdef HAVE_LIBUSB #ifdef _WIN32 #define NOGDI #endif #include <libusb-1.0/libusb.h> #endif #include "atomics_cobalt.h" #include "context-private.h" #include "device-private.h" #include "checksum.h" #include "array.h" #define ISINSTANCE(device) dc_device_isinstance((device), &atomics_cobalt_device_vtable) #define EXITCODE(rc) (rc == LIBUSB_ERROR_TIMEOUT ? DC_STATUS_TIMEOUT : DC_STATUS_IO) #define VID 0x0471 #define PID 0x0888 #define TIMEOUT 2000 #define FP_OFFSET 20 #define SZ_MEMORY (29 * 64 * 1024) #define SZ_VERSION 14 typedef struct atomics_cobalt_device_t { dc_device_t base; #ifdef HAVE_LIBUSB libusb_context *context; libusb_device_handle *handle; #endif unsigned int simulation; unsigned char fingerprint[6]; unsigned char version[SZ_VERSION]; } atomics_cobalt_device_t; static dc_status_t atomics_cobalt_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size); static dc_status_t atomics_cobalt_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata); static dc_status_t atomics_cobalt_device_close (dc_device_t *abstract); static const dc_device_vtable_t atomics_cobalt_device_vtable = { sizeof(atomics_cobalt_device_t), DC_FAMILY_ATOMICS_COBALT, atomics_cobalt_device_set_fingerprint, /* set_fingerprint */ NULL, /* read */ NULL, /* write */ NULL, /* dump */ atomics_cobalt_device_foreach, /* foreach */ NULL, /* timesync */ atomics_cobalt_device_close /* close */ }; dc_status_t atomics_cobalt_device_open (dc_device_t **out, dc_context_t *context) { #ifdef HAVE_LIBUSB dc_status_t status = DC_STATUS_SUCCESS; atomics_cobalt_device_t *device = NULL; #endif if (out == NULL) return DC_STATUS_INVALIDARGS; #ifdef HAVE_LIBUSB // Allocate memory. device = (atomics_cobalt_device_t *) dc_device_allocate (context, &atomics_cobalt_device_vtable); if (device == NULL) { ERROR (context, "Failed to allocate memory."); return DC_STATUS_NOMEMORY; } // Set the default values. device->context = NULL; device->handle = NULL; device->simulation = 0; memset (device->fingerprint, 0, sizeof (device->fingerprint)); int rc = libusb_init (&device->context); if (rc < 0) { ERROR (context, "Failed to initialize usb support."); status = DC_STATUS_IO; goto error_free; } device->handle = libusb_open_device_with_vid_pid (device->context, VID, PID); if (device->handle == NULL) { ERROR (context, "Failed to open the usb device."); status = DC_STATUS_IO; goto error_usb_exit; } rc = libusb_claim_interface (device->handle, 0); if (rc < 0) { ERROR (context, "Failed to claim the usb interface."); status = DC_STATUS_IO; goto error_usb_close; } status = atomics_cobalt_device_version ((dc_device_t *) device, device->version, sizeof (device->version)); if (status != DC_STATUS_SUCCESS) { ERROR (context, "Failed to identify the dive computer."); goto error_usb_close; } *out = (dc_device_t*) device; return DC_STATUS_SUCCESS; error_usb_close: libusb_close (device->handle); error_usb_exit: libusb_exit (device->context); error_free: dc_device_deallocate ((dc_device_t *) device); return status; #else return DC_STATUS_UNSUPPORTED; #endif } static dc_status_t atomics_cobalt_device_close (dc_device_t *abstract) { atomics_cobalt_device_t *device = (atomics_cobalt_device_t *) abstract; #ifdef HAVE_LIBUSB libusb_release_interface(device->handle, 0); libusb_close (device->handle); libusb_exit (device->context); #endif return DC_STATUS_SUCCESS; } static dc_status_t atomics_cobalt_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size) { atomics_cobalt_device_t *device = (atomics_cobalt_device_t *) abstract; if (size && size != sizeof (device->fingerprint)) return DC_STATUS_INVALIDARGS; if (size) memcpy (device->fingerprint, data, sizeof (device->fingerprint)); else memset (device->fingerprint, 0, sizeof (device->fingerprint)); return DC_STATUS_SUCCESS; } dc_status_t atomics_cobalt_device_set_simulation (dc_device_t *abstract, unsigned int simulation) { atomics_cobalt_device_t *device = (atomics_cobalt_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; device->simulation = simulation; return DC_STATUS_SUCCESS; } dc_status_t atomics_cobalt_device_version (dc_device_t *abstract, unsigned char data[], unsigned int size) { atomics_cobalt_device_t *device = (atomics_cobalt_device_t *) abstract; if (!ISINSTANCE (abstract)) return DC_STATUS_INVALIDARGS; if (size < SZ_VERSION) return DC_STATUS_INVALIDARGS; #ifdef HAVE_LIBUSB // Send the command to the dive computer. uint8_t bRequest = 0x01; int rc = libusb_control_transfer (device->handle, LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, bRequest, 0, 0, NULL, 0, TIMEOUT); if (rc != LIBUSB_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return EXITCODE(rc); } HEXDUMP (abstract->context, DC_LOGLEVEL_INFO, "Write", &bRequest, 1); // Receive the answer from the dive computer. int length = 0; unsigned char packet[SZ_VERSION + 2] = {0}; rc = libusb_bulk_transfer (device->handle, 0x82, packet, sizeof (packet), &length, TIMEOUT); if (rc != LIBUSB_SUCCESS || length != sizeof (packet)) { ERROR (abstract->context, "Failed to receive the answer."); return EXITCODE(rc); } HEXDUMP (abstract->context, DC_LOGLEVEL_INFO, "Read", packet, length); // Verify the checksum of the packet. unsigned short crc = array_uint16_le (packet + SZ_VERSION); unsigned short ccrc = checksum_add_uint16 (packet, SZ_VERSION, 0x0); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } memcpy (data, packet, SZ_VERSION); return DC_STATUS_SUCCESS; #else return DC_STATUS_UNSUPPORTED; #endif } static dc_status_t atomics_cobalt_read_dive (dc_device_t *abstract, dc_buffer_t *buffer, int init, dc_event_progress_t *progress) { #ifdef HAVE_LIBUSB atomics_cobalt_device_t *device = (atomics_cobalt_device_t *) abstract; if (device_is_cancelled (abstract)) return DC_STATUS_CANCELLED; // Erase the current contents of the buffer. if (!dc_buffer_clear (buffer)) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Send the command to the dive computer. uint8_t bRequest = 0; if (device->simulation) bRequest = init ? 0x02 : 0x03; else bRequest = init ? 0x09 : 0x0A; int rc = libusb_control_transfer (device->handle, LIBUSB_RECIPIENT_DEVICE | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, bRequest, 0, 0, NULL, 0, TIMEOUT); if (rc != LIBUSB_SUCCESS) { ERROR (abstract->context, "Failed to send the command."); return EXITCODE(rc); } HEXDUMP (abstract->context, DC_LOGLEVEL_INFO, "Write", &bRequest, 1); unsigned int nbytes = 0; while (1) { // Receive the answer from the dive computer. int length = 0; unsigned char packet[8 * 1024] = {0}; rc = libusb_bulk_transfer (device->handle, 0x82, packet, sizeof (packet), &length, TIMEOUT); if (rc != LIBUSB_SUCCESS && rc != LIBUSB_ERROR_TIMEOUT) { ERROR (abstract->context, "Failed to receive the answer."); return EXITCODE(rc); } HEXDUMP (abstract->context, DC_LOGLEVEL_INFO, "Read", packet, length); // Update and emit a progress event. if (progress) { progress->current += length; device_event_emit (abstract, DC_EVENT_PROGRESS, progress); } // Append the packet to the output buffer. dc_buffer_append (buffer, packet, length); nbytes += length; // If we received fewer bytes than requested, the transfer is finished. if (length < sizeof (packet)) break; } // Check for a buffer error. if (dc_buffer_get_size (buffer) != nbytes) { ERROR (abstract->context, "Insufficient buffer space available."); return DC_STATUS_NOMEMORY; } // Check for the minimum length. if (nbytes < 2) { ERROR (abstract->context, "Data packet is too short."); return DC_STATUS_PROTOCOL; } // When only two 0xFF bytes are received, there are no more dives. unsigned char *data = dc_buffer_get_data (buffer); if (nbytes == 2 && data[0] == 0xFF && data[1] == 0xFF) { dc_buffer_clear (buffer); return DC_STATUS_SUCCESS; } // Verify the checksum of the packet. unsigned short crc = array_uint16_le (data + nbytes - 2); unsigned short ccrc = checksum_add_uint16 (data, nbytes - 2, 0x0); if (crc != ccrc) { ERROR (abstract->context, "Unexpected answer checksum."); return DC_STATUS_PROTOCOL; } // Remove the checksum bytes. dc_buffer_slice (buffer, 0, nbytes - 2); return DC_STATUS_SUCCESS; #else return DC_STATUS_UNSUPPORTED; #endif } static dc_status_t atomics_cobalt_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata) { atomics_cobalt_device_t *device = (atomics_cobalt_device_t *) abstract; // Enable progress notifications. dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER; progress.maximum = SZ_MEMORY + 2; device_event_emit (abstract, DC_EVENT_PROGRESS, &progress); // Emit a vendor event. dc_event_vendor_t vendor; vendor.data = device->version; vendor.size = sizeof (device->version); device_event_emit (abstract, DC_EVENT_VENDOR, &vendor); // Emit a device info event. dc_event_devinfo_t devinfo; devinfo.model = array_uint16_le (device->version + 12); devinfo.firmware = (array_uint16_le (device->version + 8) << 16) + array_uint16_le (device->version + 10); devinfo.serial = 0; for (unsigned int i = 0; i < 8; ++i) { devinfo.serial *= 10; devinfo.serial += device->version[i] - '0'; } device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo); // Allocate a memory buffer. dc_buffer_t *buffer = dc_buffer_new (0); if (buffer == NULL) return DC_STATUS_NOMEMORY; unsigned int ndives = 0; dc_status_t rc = DC_STATUS_SUCCESS; while ((rc = atomics_cobalt_read_dive (abstract, buffer, (ndives == 0), &progress)) == DC_STATUS_SUCCESS) { unsigned char *data = dc_buffer_get_data (buffer); unsigned int size = dc_buffer_get_size (buffer); if (size == 0) { dc_buffer_free (buffer); return DC_STATUS_SUCCESS; } if (memcmp (data + FP_OFFSET, device->fingerprint, sizeof (device->fingerprint)) == 0) { dc_buffer_free (buffer); return DC_STATUS_SUCCESS; } if (callback && !callback (data, size, data + FP_OFFSET, sizeof (device->fingerprint), userdata)) { dc_buffer_free (buffer); return DC_STATUS_SUCCESS; } // Adjust the maximum value to take into account the two checksum bytes // for the next dive. Since we don't know the total number of dives in // advance, we can't calculate the total number of checksum bytes and // adjust the maximum on the fly. progress.maximum += 2; ndives++; } dc_buffer_free (buffer); return rc; }
libdc-for-dirk-Subsurface-branch
src/atomics_cobalt.c
#include "clar_libgit2.h" #include "util.h" void test_hex__fromhex(void) { /* Passing cases */ cl_assert(git__fromhex('0') == 0x0); cl_assert(git__fromhex('1') == 0x1); cl_assert(git__fromhex('3') == 0x3); cl_assert(git__fromhex('9') == 0x9); cl_assert(git__fromhex('A') == 0xa); cl_assert(git__fromhex('C') == 0xc); cl_assert(git__fromhex('F') == 0xf); cl_assert(git__fromhex('a') == 0xa); cl_assert(git__fromhex('c') == 0xc); cl_assert(git__fromhex('f') == 0xf); /* Failing cases */ cl_assert(git__fromhex('g') == -1); cl_assert(git__fromhex('z') == -1); cl_assert(git__fromhex('X') == -1); }
libgit2-main
tests/util/hex.c
#include "precompiled.h"
libgit2-main
tests/util/precompiled.c
#include "clar_libgit2.h" #include "fs_path.h" #ifdef GIT_USE_ICONV static git_fs_path_iconv_t ic; static char *nfc = "\xC3\x85\x73\x74\x72\xC3\xB6\x6D"; static char *nfd = "\x41\xCC\x8A\x73\x74\x72\x6F\xCC\x88\x6D"; #endif void test_iconv__initialize(void) { #ifdef GIT_USE_ICONV cl_git_pass(git_fs_path_iconv_init_precompose(&ic)); #endif } void test_iconv__cleanup(void) { #ifdef GIT_USE_ICONV git_fs_path_iconv_clear(&ic); #endif } void test_iconv__unchanged(void) { #ifdef GIT_USE_ICONV const char *data = "Ascii data", *original = data; size_t datalen = strlen(data); cl_git_pass(git_fs_path_iconv(&ic, &data, &datalen)); GIT_UNUSED(datalen); /* There are no high bits set, so this should leave data untouched */ cl_assert(data == original); #endif } void test_iconv__decomposed_to_precomposed(void) { #ifdef GIT_USE_ICONV const char *data = nfd; size_t datalen, nfdlen = strlen(nfd); datalen = nfdlen; cl_git_pass(git_fs_path_iconv(&ic, &data, &datalen)); GIT_UNUSED(datalen); /* The decomposed nfd string should be transformed to the nfc form * (on platforms where iconv is enabled, of course). */ cl_assert_equal_s(nfc, data); /* should be able to do it multiple times with the same git_fs_path_iconv_t */ data = nfd; datalen = nfdlen; cl_git_pass(git_fs_path_iconv(&ic, &data, &datalen)); cl_assert_equal_s(nfc, data); data = nfd; datalen = nfdlen; cl_git_pass(git_fs_path_iconv(&ic, &data, &datalen)); cl_assert_equal_s(nfc, data); #endif } void test_iconv__precomposed_is_unmodified(void) { #ifdef GIT_USE_ICONV const char *data = nfc; size_t datalen = strlen(nfc); cl_git_pass(git_fs_path_iconv(&ic, &data, &datalen)); GIT_UNUSED(datalen); /* data is already in precomposed form, so even though some bytes have * the high-bit set, the iconv transform should result in no change. */ cl_assert_equal_s(nfc, data); #endif }
libgit2-main
tests/util/iconv.c
#include "clar_libgit2.h" #include "wildmatch.h" #define assert_matches(string, pattern, wildmatch, iwildmatch, pathmatch, ipathmatch) \ assert_matches_(string, pattern, wildmatch, iwildmatch, pathmatch, ipathmatch, __FILE__, __func__, __LINE__) static void assert_matches_(const char *string, const char *pattern, char expected_wildmatch, char expected_iwildmatch, char expected_pathmatch, char expected_ipathmatch, const char *file, const char *func, size_t line) { if (wildmatch(pattern, string, WM_PATHNAME) == expected_wildmatch) clar__fail(file, func, line, "Test failed (wildmatch).", string, 1); if (wildmatch(pattern, string, WM_PATHNAME|WM_CASEFOLD) == expected_iwildmatch) clar__fail(file, func, line, "Test failed (iwildmatch).", string, 1); if (wildmatch(pattern, string, 0) == expected_pathmatch) clar__fail(file, func, line, "Test failed (pathmatch).", string, 1); if (wildmatch(pattern, string, WM_CASEFOLD) == expected_ipathmatch) clar__fail(file, func, line, "Test failed (ipathmatch).", string, 1); } /* * Below testcases are imported from git.git, t3070-wildmatch,sh at tag v2.22.0. * Note that we've only imported the direct wildcard tests, but not the matching * tests for git-ls-files. */ void test_wildmatch__basic_wildmatch(void) { assert_matches("foo", "foo", 1, 1, 1, 1); assert_matches("foo", "bar", 0, 0, 0, 0); assert_matches("", "", 1, 1, 1, 1); assert_matches("foo", "???", 1, 1, 1, 1); assert_matches("foo", "??", 0, 0, 0, 0); assert_matches("foo", "*", 1, 1, 1, 1); assert_matches("foo", "f*", 1, 1, 1, 1); assert_matches("foo", "*f", 0, 0, 0, 0); assert_matches("foo", "*foo*", 1, 1, 1, 1); assert_matches("foobar", "*ob*a*r*", 1, 1, 1, 1); assert_matches("aaaaaaabababab", "*ab", 1, 1, 1, 1); assert_matches("foo*", "foo\\*", 1, 1, 1, 1); assert_matches("foobar", "foo\\*bar", 0, 0, 0, 0); assert_matches("f\\oo", "f\\\\oo", 1, 1, 1, 1); assert_matches("ball", "*[al]?", 1, 1, 1, 1); assert_matches("ten", "[ten]", 0, 0, 0, 0); assert_matches("ten", "**[!te]", 1, 1, 1, 1); assert_matches("ten", "**[!ten]", 0, 0, 0, 0); assert_matches("ten", "t[a-g]n", 1, 1, 1, 1); assert_matches("ten", "t[!a-g]n", 0, 0, 0, 0); assert_matches("ton", "t[!a-g]n", 1, 1, 1, 1); assert_matches("ton", "t[^a-g]n", 1, 1, 1, 1); assert_matches("a]b", "a[]]b", 1, 1, 1, 1); assert_matches("a-b", "a[]-]b", 1, 1, 1, 1); assert_matches("a]b", "a[]-]b", 1, 1, 1, 1); assert_matches("aab", "a[]-]b", 0, 0, 0, 0); assert_matches("aab", "a[]a-]b", 1, 1, 1, 1); assert_matches("]", "]", 1, 1, 1, 1); } void test_wildmatch__slash_matching_features(void) { assert_matches("foo/baz/bar", "foo*bar", 0, 0, 1, 1); assert_matches("foo/baz/bar", "foo**bar", 0, 0, 1, 1); assert_matches("foobazbar", "foo**bar", 1, 1, 1, 1); assert_matches("foo/baz/bar", "foo/**/bar", 1, 1, 1, 1); assert_matches("foo/baz/bar", "foo/**/**/bar", 1, 1, 0, 0); assert_matches("foo/b/a/z/bar", "foo/**/bar", 1, 1, 1, 1); assert_matches("foo/b/a/z/bar", "foo/**/**/bar", 1, 1, 1, 1); assert_matches("foo/bar", "foo/**/bar", 1, 1, 0, 0); assert_matches("foo/bar", "foo/**/**/bar", 1, 1, 0, 0); assert_matches("foo/bar", "foo?bar", 0, 0, 1, 1); assert_matches("foo/bar", "foo[/]bar", 0, 0, 1, 1); assert_matches("foo/bar", "foo[^a-z]bar", 0, 0, 1, 1); assert_matches("foo/bar", "f[^eiu][^eiu][^eiu][^eiu][^eiu]r", 0, 0, 1, 1); assert_matches("foo-bar", "f[^eiu][^eiu][^eiu][^eiu][^eiu]r", 1, 1, 1, 1); assert_matches("foo", "**/foo", 1, 1, 0, 0); assert_matches("XXX/foo", "**/foo", 1, 1, 1, 1); assert_matches("bar/baz/foo", "**/foo", 1, 1, 1, 1); assert_matches("bar/baz/foo", "*/foo", 0, 0, 1, 1); assert_matches("foo/bar/baz", "**/bar*", 0, 0, 1, 1); assert_matches("deep/foo/bar/baz", "**/bar/*", 1, 1, 1, 1); assert_matches("deep/foo/bar/baz/", "**/bar/*", 0, 0, 1, 1); assert_matches("deep/foo/bar/baz/", "**/bar/**", 1, 1, 1, 1); assert_matches("deep/foo/bar", "**/bar/*", 0, 0, 0, 0); assert_matches("deep/foo/bar/", "**/bar/**", 1, 1, 1, 1); assert_matches("foo/bar/baz", "**/bar**", 0, 0, 1, 1); assert_matches("foo/bar/baz/x", "*/bar/**", 1, 1, 1, 1); assert_matches("deep/foo/bar/baz/x", "*/bar/**", 0, 0, 1, 1); assert_matches("deep/foo/bar/baz/x", "**/bar/*/*", 1, 1, 1, 1); } void test_wildmatch__various_additional(void) { assert_matches("acrt", "a[c-c]st", 0, 0, 0, 0); assert_matches("acrt", "a[c-c]rt", 1, 1, 1, 1); assert_matches("]", "[!]-]", 0, 0, 0, 0); assert_matches("a", "[!]-]", 1, 1, 1, 1); assert_matches("", "\\", 0, 0, 0, 0); assert_matches("\\", "\\", 0, 0, 0, 0); assert_matches("XXX/\\", "*/\\", 0, 0, 0, 0); assert_matches("XXX/\\", "*/\\\\", 1, 1, 1, 1); assert_matches("foo", "foo", 1, 1, 1, 1); assert_matches("@foo", "@foo", 1, 1, 1, 1); assert_matches("foo", "@foo", 0, 0, 0, 0); assert_matches("[ab]", "\\[ab]", 1, 1, 1, 1); assert_matches("[ab]", "[[]ab]", 1, 1, 1, 1); assert_matches("[ab]", "[[:]ab]", 1, 1, 1, 1); assert_matches("[ab]", "[[::]ab]", 0, 0, 0, 0); assert_matches("[ab]", "[[:digit]ab]", 1, 1, 1, 1); assert_matches("[ab]", "[\\[:]ab]", 1, 1, 1, 1); assert_matches("?a?b", "\\??\\?b", 1, 1, 1, 1); assert_matches("abc", "\\a\\b\\c", 1, 1, 1, 1); assert_matches("foo", "", 0, 0, 0, 0); assert_matches("foo/bar/baz/to", "**/t[o]", 1, 1, 1, 1); } void test_wildmatch__character_classes(void) { assert_matches("a1B", "[[:alpha:]][[:digit:]][[:upper:]]", 1, 1, 1, 1); assert_matches("a", "[[:digit:][:upper:][:space:]]", 0, 1, 0, 1); assert_matches("A", "[[:digit:][:upper:][:space:]]", 1, 1, 1, 1); assert_matches("1", "[[:digit:][:upper:][:space:]]", 1, 1, 1, 1); assert_matches("1", "[[:digit:][:upper:][:spaci:]]", 0, 0, 0, 0); assert_matches(" ", "[[:digit:][:upper:][:space:]]", 1, 1, 1, 1); assert_matches(".", "[[:digit:][:upper:][:space:]]", 0, 0, 0, 0); assert_matches(".", "[[:digit:][:punct:][:space:]]", 1, 1, 1, 1); assert_matches("5", "[[:xdigit:]]", 1, 1, 1, 1); assert_matches("f", "[[:xdigit:]]", 1, 1, 1, 1); assert_matches("D", "[[:xdigit:]]", 1, 1, 1, 1); assert_matches("_", "[[:alnum:][:alpha:][:blank:][:cntrl:][:digit:][:graph:][:lower:][:print:][:punct:][:space:][:upper:][:xdigit:]]", 1, 1, 1, 1); assert_matches(".", "[^[:alnum:][:alpha:][:blank:][:cntrl:][:digit:][:lower:][:space:][:upper:][:xdigit:]]", 1, 1, 1, 1); assert_matches("5", "[a-c[:digit:]x-z]", 1, 1, 1, 1); assert_matches("b", "[a-c[:digit:]x-z]", 1, 1, 1, 1); assert_matches("y", "[a-c[:digit:]x-z]", 1, 1, 1, 1); assert_matches("q", "[a-c[:digit:]x-z]", 0, 0, 0, 0); } void test_wildmatch__additional_with_malformed(void) { assert_matches("]", "[\\\\-^]", 1, 1, 1, 1); assert_matches("[", "[\\\\-^]", 0, 0, 0, 0); assert_matches("-", "[\\-_]", 1, 1, 1, 1); assert_matches("]", "[\\]]", 1, 1, 1, 1); assert_matches("\\]", "[\\]]", 0, 0, 0, 0); assert_matches("\\", "[\\]]", 0, 0, 0, 0); assert_matches("ab", "a[]b", 0, 0, 0, 0); assert_matches("a[]b", "a[]b", 0, 0, 0, 0); assert_matches("ab[", "ab[", 0, 0, 0, 0); assert_matches("ab", "[!", 0, 0, 0, 0); assert_matches("ab", "[-", 0, 0, 0, 0); assert_matches("-", "[-]", 1, 1, 1, 1); assert_matches("-", "[a-", 0, 0, 0, 0); assert_matches("-", "[!a-", 0, 0, 0, 0); assert_matches("-", "[--A]", 1, 1, 1, 1); assert_matches("5", "[--A]", 1, 1, 1, 1); assert_matches(" ", "[ --]", 1, 1, 1, 1); assert_matches("$", "[ --]", 1, 1, 1, 1); assert_matches("-", "[ --]", 1, 1, 1, 1); assert_matches("0", "[ --]", 0, 0, 0, 0); assert_matches("-", "[---]", 1, 1, 1, 1); assert_matches("-", "[------]", 1, 1, 1, 1); assert_matches("j", "[a-e-n]", 0, 0, 0, 0); assert_matches("-", "[a-e-n]", 1, 1, 1, 1); assert_matches("a", "[!------]", 1, 1, 1, 1); assert_matches("[", "[]-a]", 0, 0, 0, 0); assert_matches("^", "[]-a]", 1, 1, 1, 1); assert_matches("^", "[!]-a]", 0, 0, 0, 0); assert_matches("[", "[!]-a]", 1, 1, 1, 1); assert_matches("^", "[a^bc]", 1, 1, 1, 1); assert_matches("-b]", "[a-]b]", 1, 1, 1, 1); assert_matches("\\", "[\\]", 0, 0, 0, 0); assert_matches("\\", "[\\\\]", 1, 1, 1, 1); assert_matches("\\", "[!\\\\]", 0, 0, 0, 0); assert_matches("G", "[A-\\\\]", 1, 1, 1, 1); assert_matches("aaabbb", "b*a", 0, 0, 0, 0); assert_matches("aabcaa", "*ba*", 0, 0, 0, 0); assert_matches(",", "[,]", 1, 1, 1, 1); assert_matches(",", "[\\\\,]", 1, 1, 1, 1); assert_matches("\\", "[\\\\,]", 1, 1, 1, 1); assert_matches("-", "[,-.]", 1, 1, 1, 1); assert_matches("+", "[,-.]", 0, 0, 0, 0); assert_matches("-.]", "[,-.]", 0, 0, 0, 0); assert_matches("2", "[\\1-\\3]", 1, 1, 1, 1); assert_matches("3", "[\\1-\\3]", 1, 1, 1, 1); assert_matches("4", "[\\1-\\3]", 0, 0, 0, 0); assert_matches("\\", "[[-\\]]", 1, 1, 1, 1); assert_matches("[", "[[-\\]]", 1, 1, 1, 1); assert_matches("]", "[[-\\]]", 1, 1, 1, 1); assert_matches("-", "[[-\\]]", 0, 0, 0, 0); } void test_wildmatch__recursion(void) { assert_matches("-adobe-courier-bold-o-normal--12-120-75-75-m-70-iso8859-1", "-*-*-*-*-*-*-12-*-*-*-m-*-*-*", 1, 1, 1, 1); assert_matches("-adobe-courier-bold-o-normal--12-120-75-75-X-70-iso8859-1", "-*-*-*-*-*-*-12-*-*-*-m-*-*-*", 0, 0, 0, 0); assert_matches("-adobe-courier-bold-o-normal--12-120-75-75-/-70-iso8859-1", "-*-*-*-*-*-*-12-*-*-*-m-*-*-*", 0, 0, 0, 0); assert_matches("XXX/adobe/courier/bold/o/normal//12/120/75/75/m/70/iso8859/1", "XXX/*/*/*/*/*/*/12/*/*/*/m/*/*/*", 1, 1, 1, 1); assert_matches("XXX/adobe/courier/bold/o/normal//12/120/75/75/X/70/iso8859/1", "XXX/*/*/*/*/*/*/12/*/*/*/m/*/*/*", 0, 0, 0, 0); assert_matches("abcd/abcdefg/abcdefghijk/abcdefghijklmnop.txt", "**/*a*b*g*n*t", 1, 1, 1, 1); assert_matches("abcd/abcdefg/abcdefghijk/abcdefghijklmnop.txtz", "**/*a*b*g*n*t", 0, 0, 0, 0); assert_matches("foo", "*/*/*", 0, 0, 0, 0); assert_matches("foo/bar", "*/*/*", 0, 0, 0, 0); assert_matches("foo/bba/arr", "*/*/*", 1, 1, 1, 1); assert_matches("foo/bb/aa/rr", "*/*/*", 0, 0, 1, 1); assert_matches("foo/bb/aa/rr", "**/**/**", 1, 1, 1, 1); assert_matches("abcXdefXghi", "*X*i", 1, 1, 1, 1); assert_matches("ab/cXd/efXg/hi", "*X*i", 0, 0, 1, 1); assert_matches("ab/cXd/efXg/hi", "*/*X*/*/*i", 1, 1, 1, 1); assert_matches("ab/cXd/efXg/hi", "**/*X*/**/*i", 1, 1, 1, 1); } void test_wildmatch__pathmatch(void) { assert_matches("foo", "fo", 0, 0, 0, 0); assert_matches("foo/bar", "foo/bar", 1, 1, 1, 1); assert_matches("foo/bar", "foo/*", 1, 1, 1, 1); assert_matches("foo/bba/arr", "foo/*", 0, 0, 1, 1); assert_matches("foo/bba/arr", "foo/**", 1, 1, 1, 1); assert_matches("foo/bba/arr", "foo*", 0, 0, 1, 1); assert_matches("foo/bba/arr", "foo**", 0, 0, 1, 1); assert_matches("foo/bba/arr", "foo/*arr", 0, 0, 1, 1); assert_matches("foo/bba/arr", "foo/**arr", 0, 0, 1, 1); assert_matches("foo/bba/arr", "foo/*z", 0, 0, 0, 0); assert_matches("foo/bba/arr", "foo/**z", 0, 0, 0, 0); assert_matches("foo/bar", "foo?bar", 0, 0, 1, 1); assert_matches("foo/bar", "foo[/]bar", 0, 0, 1, 1); assert_matches("foo/bar", "foo[^a-z]bar", 0, 0, 1, 1); assert_matches("ab/cXd/efXg/hi", "*Xg*i", 0, 0, 1, 1); } void test_wildmatch__case_sensitivity(void) { assert_matches("a", "[A-Z]", 0, 1, 0, 1); assert_matches("A", "[A-Z]", 1, 1, 1, 1); assert_matches("A", "[a-z]", 0, 1, 0, 1); assert_matches("a", "[a-z]", 1, 1, 1, 1); assert_matches("a", "[[:upper:]]", 0, 1, 0, 1); assert_matches("A", "[[:upper:]]", 1, 1, 1, 1); assert_matches("A", "[[:lower:]]", 0, 1, 0, 1); assert_matches("a", "[[:lower:]]", 1, 1, 1, 1); assert_matches("A", "[B-Za]", 0, 1, 0, 1); assert_matches("a", "[B-Za]", 1, 1, 1, 1); assert_matches("A", "[B-a]", 0, 1, 0, 1); assert_matches("a", "[B-a]", 1, 1, 1, 1); assert_matches("z", "[Z-y]", 0, 1, 0, 1); assert_matches("Z", "[Z-y]", 1, 1, 1, 1); }
libgit2-main
tests/util/wildmatch.c
/** * Some tests for p_ftruncate() to ensure that * properly handles large (2Gb+) files. */ #include "clar_libgit2.h" static const char *filename = "core_ftruncate.txt"; static int fd = -1; void test_ftruncate__initialize(void) { if (!cl_is_env_set("GITTEST_INVASIVE_FS_SIZE")) cl_skip(); cl_must_pass((fd = p_open(filename, O_CREAT | O_RDWR, 0644))); } void test_ftruncate__cleanup(void) { if (fd < 0) return; p_close(fd); fd = 0; p_unlink(filename); } static void _extend(off64_t i64len) { struct stat st; int error; cl_assert((error = p_ftruncate(fd, i64len)) == 0); cl_assert((error = p_fstat(fd, &st)) == 0); cl_assert(st.st_size == i64len); } void test_ftruncate__2gb(void) { _extend(0x80000001); } void test_ftruncate__4gb(void) { _extend(0x100000001); }
libgit2-main
tests/util/ftruncate.c
#include "clar_libgit2.h" #include "array.h" static int int_lookup(const void *k, const void *a) { const int *one = (const int *)k; int *two = (int *)a; return *one - *two; } #define expect_pos(k, n, ret) \ key = (k); \ cl_assert_equal_i((ret), \ git_array_search(&p, integers, int_lookup, &key)); \ cl_assert_equal_i((n), p); void test_array__bsearch2(void) { git_array_t(int) integers = GIT_ARRAY_INIT; int *i, key; size_t p; i = git_array_alloc(integers); *i = 2; i = git_array_alloc(integers); *i = 3; i = git_array_alloc(integers); *i = 5; i = git_array_alloc(integers); *i = 7; i = git_array_alloc(integers); *i = 7; i = git_array_alloc(integers); *i = 8; i = git_array_alloc(integers); *i = 13; i = git_array_alloc(integers); *i = 21; i = git_array_alloc(integers); *i = 25; i = git_array_alloc(integers); *i = 42; i = git_array_alloc(integers); *i = 69; i = git_array_alloc(integers); *i = 121; i = git_array_alloc(integers); *i = 256; i = git_array_alloc(integers); *i = 512; i = git_array_alloc(integers); *i = 513; i = git_array_alloc(integers); *i = 514; i = git_array_alloc(integers); *i = 516; i = git_array_alloc(integers); *i = 516; i = git_array_alloc(integers); *i = 517; /* value to search for, expected position, return code */ expect_pos(3, 1, GIT_OK); expect_pos(2, 0, GIT_OK); expect_pos(1, 0, GIT_ENOTFOUND); expect_pos(25, 8, GIT_OK); expect_pos(26, 9, GIT_ENOTFOUND); expect_pos(42, 9, GIT_OK); expect_pos(50, 10, GIT_ENOTFOUND); expect_pos(68, 10, GIT_ENOTFOUND); expect_pos(256, 12, GIT_OK); git_array_clear(integers); }
libgit2-main
tests/util/array.c
#ifndef _WIN32 # include <arpa/inet.h> # include <sys/socket.h> # include <netinet/in.h> #else # include <ws2tcpip.h> # ifdef _MSC_VER # pragma comment(lib, "ws2_32") # endif #endif #include "clar_libgit2.h" #include "futils.h" #include "posix.h" void test_posix__initialize(void) { #ifdef GIT_WIN32 /* on win32, the WSA context needs to be initialized * before any socket calls can be performed */ WSADATA wsd; cl_git_pass(WSAStartup(MAKEWORD(2,2), &wsd)); cl_assert(LOBYTE(wsd.wVersion) == 2 && HIBYTE(wsd.wVersion) == 2); #endif } static bool supports_ipv6(void) { #ifdef GIT_WIN32 /* IPv6 is supported on Vista and newer */ return git_has_win32_version(6, 0, 0); #else return 1; #endif } void test_posix__inet_pton(void) { struct in_addr addr; struct in6_addr addr6; size_t i; struct in_addr_data { const char *p; const uint8_t n[4]; }; struct in6_addr_data { const char *p; const uint8_t n[16]; }; static struct in_addr_data in_addr_data[] = { { "0.0.0.0", { 0, 0, 0, 0 } }, { "10.42.101.8", { 10, 42, 101, 8 } }, { "127.0.0.1", { 127, 0, 0, 1 } }, { "140.177.10.12", { 140, 177, 10, 12 } }, { "204.232.175.90", { 204, 232, 175, 90 } }, { "255.255.255.255", { 255, 255, 255, 255 } }, }; static struct in6_addr_data in6_addr_data[] = { { "::", { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }, { "::1", { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 } }, { "0:0:0:0:0:0:0:1", { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 } }, { "2001:db8:8714:3a90::12", { 0x20, 0x01, 0x0d, 0xb8, 0x87, 0x14, 0x3a, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12 } }, { "fe80::f8ba:c2d6:86be:3645", { 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xba, 0xc2, 0xd6, 0x86, 0xbe, 0x36, 0x45 } }, { "::ffff:204.152.189.116", { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xcc, 0x98, 0xbd, 0x74 } }, }; /* Test some ipv4 addresses */ for (i = 0; i < 6; i++) { cl_assert(p_inet_pton(AF_INET, in_addr_data[i].p, &addr) == 1); cl_assert(memcmp(&addr, in_addr_data[i].n, sizeof(struct in_addr)) == 0); } /* Test some ipv6 addresses */ if (supports_ipv6()) { for (i = 0; i < 6; i++) { cl_assert(p_inet_pton(AF_INET6, in6_addr_data[i].p, &addr6) == 1); cl_assert(memcmp(&addr6, in6_addr_data[i].n, sizeof(struct in6_addr)) == 0); } } /* Test some invalid strings */ cl_assert(p_inet_pton(AF_INET, "", &addr) == 0); cl_assert(p_inet_pton(AF_INET, "foo", &addr) == 0); cl_assert(p_inet_pton(AF_INET, " 127.0.0.1", &addr) == 0); cl_assert(p_inet_pton(AF_INET, "bar", &addr) == 0); cl_assert(p_inet_pton(AF_INET, "10.foo.bar.1", &addr) == 0); /* Test unsupported address families */ cl_git_fail(p_inet_pton(INT_MAX-1, "52.472", &addr)); cl_assert_equal_i(EAFNOSUPPORT, errno); } void test_posix__utimes(void) { struct p_timeval times[2]; struct stat st; time_t curtime; int fd; /* test p_utimes */ times[0].tv_sec = 1234567890; times[0].tv_usec = 0; times[1].tv_sec = 1234567890; times[1].tv_usec = 0; cl_git_mkfile("foo", "Dummy file."); cl_must_pass(p_utimes("foo", times)); cl_must_pass(p_stat("foo", &st)); cl_assert_equal_i(1234567890, st.st_atime); cl_assert_equal_i(1234567890, st.st_mtime); /* test p_futimes */ times[0].tv_sec = 1414141414; times[0].tv_usec = 0; times[1].tv_sec = 1414141414; times[1].tv_usec = 0; cl_must_pass(fd = p_open("foo", O_RDWR)); cl_must_pass(p_futimes(fd, times)); cl_must_pass(p_close(fd)); cl_must_pass(p_stat("foo", &st)); cl_assert_equal_i(1414141414, st.st_atime); cl_assert_equal_i(1414141414, st.st_mtime); /* test p_utimes with current time, assume that * it takes < 5 seconds to get the time...! */ cl_must_pass(p_utimes("foo", NULL)); curtime = time(NULL); cl_must_pass(p_stat("foo", &st)); cl_assert((st.st_atime - curtime) < 5); cl_assert((st.st_mtime - curtime) < 5); cl_must_pass(p_unlink("foo")); } void test_posix__unlink_removes_symlink(void) { if (!git_fs_path_supports_symlinks(clar_sandbox_path())) clar__skip(); cl_git_mkfile("file", "Dummy file."); cl_git_pass(git_futils_mkdir("dir", 0777, 0)); cl_must_pass(p_symlink("file", "file-symlink")); cl_must_pass(p_symlink("dir", "dir-symlink")); cl_must_pass(p_unlink("file-symlink")); cl_must_pass(p_unlink("dir-symlink")); cl_assert(git_fs_path_exists("file")); cl_assert(git_fs_path_exists("dir")); cl_must_pass(p_unlink("file")); cl_must_pass(p_rmdir("dir")); } void test_posix__symlink_resolves_to_correct_type(void) { git_str contents = GIT_STR_INIT; if (!git_fs_path_supports_symlinks(clar_sandbox_path())) clar__skip(); cl_must_pass(git_futils_mkdir("dir", 0777, 0)); cl_must_pass(git_futils_mkdir("file", 0777, 0)); cl_git_mkfile("dir/file", "symlink target"); cl_git_pass(p_symlink("file", "dir/link")); cl_git_pass(git_futils_readbuffer(&contents, "dir/file")); cl_assert_equal_s(contents.ptr, "symlink target"); cl_must_pass(p_unlink("dir/link")); cl_must_pass(p_unlink("dir/file")); cl_must_pass(p_rmdir("dir")); cl_must_pass(p_rmdir("file")); git_str_dispose(&contents); } void test_posix__relative_symlink(void) { git_str contents = GIT_STR_INIT; if (!git_fs_path_supports_symlinks(clar_sandbox_path())) clar__skip(); cl_must_pass(git_futils_mkdir("dir", 0777, 0)); cl_git_mkfile("file", "contents"); cl_git_pass(p_symlink("../file", "dir/link")); cl_git_pass(git_futils_readbuffer(&contents, "dir/link")); cl_assert_equal_s(contents.ptr, "contents"); cl_must_pass(p_unlink("file")); cl_must_pass(p_unlink("dir/link")); cl_must_pass(p_rmdir("dir")); git_str_dispose(&contents); } void test_posix__symlink_to_file_across_dirs(void) { git_str contents = GIT_STR_INIT; if (!git_fs_path_supports_symlinks(clar_sandbox_path())) clar__skip(); /* * Create a relative symlink that points into another * directory. This used to not work on Win32, where we * forgot to convert directory separators to * Windows-style ones. */ cl_must_pass(git_futils_mkdir("dir", 0777, 0)); cl_git_mkfile("dir/target", "symlink target"); cl_git_pass(p_symlink("dir/target", "link")); cl_git_pass(git_futils_readbuffer(&contents, "dir/target")); cl_assert_equal_s(contents.ptr, "symlink target"); cl_must_pass(p_unlink("dir/target")); cl_must_pass(p_unlink("link")); cl_must_pass(p_rmdir("dir")); git_str_dispose(&contents); }
libgit2-main
tests/util/posix.c
#include "clar_libgit2.h" #include "posix.h" #ifdef GIT_WIN32 # include "win32/reparse.h" #endif void test_link__cleanup(void) { #ifdef GIT_WIN32 RemoveDirectory("lstat_junction"); RemoveDirectory("lstat_dangling"); RemoveDirectory("lstat_dangling_dir"); RemoveDirectory("lstat_dangling_junction"); RemoveDirectory("stat_junction"); RemoveDirectory("stat_dangling"); RemoveDirectory("stat_dangling_dir"); RemoveDirectory("stat_dangling_junction"); #endif } #ifdef GIT_WIN32 static bool should_run(void) { static SID_IDENTIFIER_AUTHORITY authority = { SECURITY_NT_AUTHORITY }; PSID admin_sid; BOOL is_admin; cl_win32_pass(AllocateAndInitializeSid(&authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &admin_sid)); cl_win32_pass(CheckTokenMembership(NULL, admin_sid, &is_admin)); FreeSid(admin_sid); return is_admin ? true : false; } #else static bool should_run(void) { return true; } #endif static void do_symlink(const char *old, const char *new, int is_dir) { #ifndef GIT_WIN32 GIT_UNUSED(is_dir); cl_must_pass(symlink(old, new)); #else typedef DWORD (WINAPI *create_symlink_func)(LPCTSTR, LPCTSTR, DWORD); HMODULE module; create_symlink_func pCreateSymbolicLink; cl_assert(module = GetModuleHandle("kernel32")); cl_assert(pCreateSymbolicLink = (create_symlink_func)(void *)GetProcAddress(module, "CreateSymbolicLinkA")); cl_win32_pass(pCreateSymbolicLink(new, old, is_dir)); #endif } static void do_hardlink(const char *old, const char *new) { #ifndef GIT_WIN32 cl_must_pass(link(old, new)); #else typedef DWORD (WINAPI *create_hardlink_func)(LPCTSTR, LPCTSTR, LPSECURITY_ATTRIBUTES); HMODULE module; create_hardlink_func pCreateHardLink; cl_assert(module = GetModuleHandle("kernel32")); cl_assert(pCreateHardLink = (create_hardlink_func)(void *)GetProcAddress(module, "CreateHardLinkA")); cl_win32_pass(pCreateHardLink(new, old, 0)); #endif } #ifdef GIT_WIN32 static void do_junction(const char *old, const char *new) { GIT_REPARSE_DATA_BUFFER *reparse_buf; HANDLE handle; git_str unparsed_buf = GIT_STR_INIT; wchar_t *subst_utf16, *print_utf16; DWORD ioctl_ret; int subst_utf16_len, subst_byte_len, print_utf16_len, print_byte_len, ret; USHORT reparse_buflen; size_t i; /* Junction targets must be the unparsed name, starting with \??\, using * backslashes instead of forward, and end in a trailing backslash. * eg: \??\C:\Foo\ */ git_str_puts(&unparsed_buf, "\\??\\"); for (i = 0; i < strlen(old); i++) git_str_putc(&unparsed_buf, old[i] == '/' ? '\\' : old[i]); git_str_putc(&unparsed_buf, '\\'); subst_utf16_len = git__utf8_to_16(NULL, 0, git_str_cstr(&unparsed_buf)); subst_byte_len = subst_utf16_len * sizeof(WCHAR); print_utf16_len = subst_utf16_len - 4; print_byte_len = subst_byte_len - (4 * sizeof(WCHAR)); /* The junction must be an empty directory before the junction attribute * can be added. */ cl_win32_pass(CreateDirectoryA(new, NULL)); handle = CreateFileA(new, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL); cl_win32_pass(handle != INVALID_HANDLE_VALUE); reparse_buflen = (USHORT)(REPARSE_DATA_HEADER_SIZE + REPARSE_DATA_MOUNTPOINT_HEADER_SIZE + subst_byte_len + sizeof(WCHAR) + print_byte_len + sizeof(WCHAR)); reparse_buf = LocalAlloc(LMEM_FIXED|LMEM_ZEROINIT, reparse_buflen); cl_assert(reparse_buf); subst_utf16 = reparse_buf->ReparseBuffer.MountPoint.PathBuffer; print_utf16 = subst_utf16 + subst_utf16_len + 1; ret = git__utf8_to_16(subst_utf16, subst_utf16_len + 1, git_str_cstr(&unparsed_buf)); cl_assert_equal_i(subst_utf16_len, ret); ret = git__utf8_to_16(print_utf16, print_utf16_len + 1, git_str_cstr(&unparsed_buf) + 4); cl_assert_equal_i(print_utf16_len, ret); reparse_buf->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; reparse_buf->ReparseBuffer.MountPoint.SubstituteNameOffset = 0; reparse_buf->ReparseBuffer.MountPoint.SubstituteNameLength = subst_byte_len; reparse_buf->ReparseBuffer.MountPoint.PrintNameOffset = (USHORT)(subst_byte_len + sizeof(WCHAR)); reparse_buf->ReparseBuffer.MountPoint.PrintNameLength = print_byte_len; reparse_buf->ReparseDataLength = reparse_buflen - REPARSE_DATA_HEADER_SIZE; cl_win32_pass(DeviceIoControl(handle, FSCTL_SET_REPARSE_POINT, reparse_buf, reparse_buflen, NULL, 0, &ioctl_ret, NULL)); CloseHandle(handle); LocalFree(reparse_buf); git_str_dispose(&unparsed_buf); } static void do_custom_reparse(const char *path) { REPARSE_GUID_DATA_BUFFER *reparse_buf; HANDLE handle; DWORD ioctl_ret; const char *reparse_data = "Reparse points are silly."; size_t reparse_buflen = REPARSE_GUID_DATA_BUFFER_HEADER_SIZE + strlen(reparse_data) + 1; reparse_buf = LocalAlloc(LMEM_FIXED|LMEM_ZEROINIT, reparse_buflen); cl_assert(reparse_buf); reparse_buf->ReparseTag = 42; reparse_buf->ReparseDataLength = (WORD)(strlen(reparse_data) + 1); reparse_buf->ReparseGuid.Data1 = 0xdeadbeef; reparse_buf->ReparseGuid.Data2 = 0xdead; reparse_buf->ReparseGuid.Data3 = 0xbeef; reparse_buf->ReparseGuid.Data4[0] = 42; reparse_buf->ReparseGuid.Data4[1] = 42; reparse_buf->ReparseGuid.Data4[2] = 42; reparse_buf->ReparseGuid.Data4[3] = 42; reparse_buf->ReparseGuid.Data4[4] = 42; reparse_buf->ReparseGuid.Data4[5] = 42; reparse_buf->ReparseGuid.Data4[6] = 42; reparse_buf->ReparseGuid.Data4[7] = 42; reparse_buf->ReparseGuid.Data4[8] = 42; memcpy(reparse_buf->GenericReparseBuffer.DataBuffer, reparse_data, strlen(reparse_data) + 1); handle = CreateFileA(path, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL); cl_win32_pass(handle != INVALID_HANDLE_VALUE); cl_win32_pass(DeviceIoControl(handle, FSCTL_SET_REPARSE_POINT, reparse_buf, reparse_buf->ReparseDataLength + REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, NULL, 0, &ioctl_ret, NULL)); CloseHandle(handle); LocalFree(reparse_buf); } #endif void test_link__stat_regular_file(void) { struct stat st; cl_git_rewritefile("stat_regfile", "This is a regular file!\n"); cl_must_pass(p_stat("stat_regfile", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(24, st.st_size); } void test_link__lstat_regular_file(void) { struct stat st; cl_git_rewritefile("lstat_regfile", "This is a regular file!\n"); cl_must_pass(p_stat("lstat_regfile", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(24, st.st_size); } void test_link__stat_symlink(void) { struct stat st; if (!should_run()) clar__skip(); cl_git_rewritefile("stat_target", "This is the target of a symbolic link.\n"); do_symlink("stat_target", "stat_symlink", 0); cl_must_pass(p_stat("stat_target", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(39, st.st_size); cl_must_pass(p_stat("stat_symlink", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(39, st.st_size); } void test_link__stat_symlink_directory(void) { struct stat st; if (!should_run()) clar__skip(); p_mkdir("stat_dirtarget", 0777); do_symlink("stat_dirtarget", "stat_dirlink", 1); cl_must_pass(p_stat("stat_dirtarget", &st)); cl_assert(S_ISDIR(st.st_mode)); cl_must_pass(p_stat("stat_dirlink", &st)); cl_assert(S_ISDIR(st.st_mode)); } void test_link__stat_symlink_chain(void) { struct stat st; if (!should_run()) clar__skip(); cl_git_rewritefile("stat_final_target", "Final target of some symbolic links...\n"); do_symlink("stat_final_target", "stat_chain_3", 0); do_symlink("stat_chain_3", "stat_chain_2", 0); do_symlink("stat_chain_2", "stat_chain_1", 0); cl_must_pass(p_stat("stat_chain_1", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(39, st.st_size); } void test_link__stat_dangling_symlink(void) { struct stat st; if (!should_run()) clar__skip(); do_symlink("stat_nonexistent", "stat_dangling", 0); cl_must_fail(p_stat("stat_nonexistent", &st)); cl_must_fail(p_stat("stat_dangling", &st)); } void test_link__stat_dangling_symlink_directory(void) { struct stat st; if (!should_run()) clar__skip(); do_symlink("stat_nonexistent", "stat_dangling_dir", 1); cl_must_fail(p_stat("stat_nonexistent_dir", &st)); cl_must_fail(p_stat("stat_dangling", &st)); } void test_link__lstat_symlink(void) { git_str target_path = GIT_STR_INIT; struct stat st; if (!should_run()) clar__skip(); /* Windows always writes the canonical path as the link target, so * write the full path on all platforms. */ git_str_join(&target_path, '/', clar_sandbox_path(), "lstat_target"); cl_git_rewritefile("lstat_target", "This is the target of a symbolic link.\n"); do_symlink(git_str_cstr(&target_path), "lstat_symlink", 0); cl_must_pass(p_lstat("lstat_target", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(39, st.st_size); cl_must_pass(p_lstat("lstat_symlink", &st)); cl_assert(S_ISLNK(st.st_mode)); cl_assert_equal_i(git_str_len(&target_path), st.st_size); git_str_dispose(&target_path); } void test_link__lstat_symlink_directory(void) { git_str target_path = GIT_STR_INIT; struct stat st; if (!should_run()) clar__skip(); git_str_join(&target_path, '/', clar_sandbox_path(), "lstat_dirtarget"); p_mkdir("lstat_dirtarget", 0777); do_symlink(git_str_cstr(&target_path), "lstat_dirlink", 1); cl_must_pass(p_lstat("lstat_dirtarget", &st)); cl_assert(S_ISDIR(st.st_mode)); cl_must_pass(p_lstat("lstat_dirlink", &st)); cl_assert(S_ISLNK(st.st_mode)); cl_assert_equal_i(git_str_len(&target_path), st.st_size); git_str_dispose(&target_path); } void test_link__lstat_dangling_symlink(void) { struct stat st; if (!should_run()) clar__skip(); do_symlink("lstat_nonexistent", "lstat_dangling", 0); cl_must_fail(p_lstat("lstat_nonexistent", &st)); cl_must_pass(p_lstat("lstat_dangling", &st)); cl_assert(S_ISLNK(st.st_mode)); cl_assert_equal_i(strlen("lstat_nonexistent"), st.st_size); } void test_link__lstat_dangling_symlink_directory(void) { struct stat st; if (!should_run()) clar__skip(); do_symlink("lstat_nonexistent", "lstat_dangling_dir", 1); cl_must_fail(p_lstat("lstat_nonexistent", &st)); cl_must_pass(p_lstat("lstat_dangling_dir", &st)); cl_assert(S_ISLNK(st.st_mode)); cl_assert_equal_i(strlen("lstat_nonexistent"), st.st_size); } void test_link__stat_junction(void) { #ifdef GIT_WIN32 git_str target_path = GIT_STR_INIT; struct stat st; git_str_join(&target_path, '/', clar_sandbox_path(), "stat_junctarget"); p_mkdir("stat_junctarget", 0777); do_junction(git_str_cstr(&target_path), "stat_junction"); cl_must_pass(p_stat("stat_junctarget", &st)); cl_assert(S_ISDIR(st.st_mode)); cl_must_pass(p_stat("stat_junction", &st)); cl_assert(S_ISDIR(st.st_mode)); git_str_dispose(&target_path); #endif } void test_link__stat_dangling_junction(void) { #ifdef GIT_WIN32 git_str target_path = GIT_STR_INIT; struct stat st; git_str_join(&target_path, '/', clar_sandbox_path(), "stat_nonexistent_junctarget"); p_mkdir("stat_nonexistent_junctarget", 0777); do_junction(git_str_cstr(&target_path), "stat_dangling_junction"); RemoveDirectory("stat_nonexistent_junctarget"); cl_must_fail(p_stat("stat_nonexistent_junctarget", &st)); cl_must_fail(p_stat("stat_dangling_junction", &st)); git_str_dispose(&target_path); #endif } void test_link__lstat_junction(void) { #ifdef GIT_WIN32 git_str target_path = GIT_STR_INIT; struct stat st; git_str_join(&target_path, '/', clar_sandbox_path(), "lstat_junctarget"); p_mkdir("lstat_junctarget", 0777); do_junction(git_str_cstr(&target_path), "lstat_junction"); cl_must_pass(p_lstat("lstat_junctarget", &st)); cl_assert(S_ISDIR(st.st_mode)); cl_must_pass(p_lstat("lstat_junction", &st)); cl_assert(S_ISLNK(st.st_mode)); git_str_dispose(&target_path); #endif } void test_link__lstat_dangling_junction(void) { #ifdef GIT_WIN32 git_str target_path = GIT_STR_INIT; struct stat st; git_str_join(&target_path, '/', clar_sandbox_path(), "lstat_nonexistent_junctarget"); p_mkdir("lstat_nonexistent_junctarget", 0777); do_junction(git_str_cstr(&target_path), "lstat_dangling_junction"); RemoveDirectory("lstat_nonexistent_junctarget"); cl_must_fail(p_lstat("lstat_nonexistent_junctarget", &st)); cl_must_pass(p_lstat("lstat_dangling_junction", &st)); cl_assert(S_ISLNK(st.st_mode)); cl_assert_equal_i(git_str_len(&target_path), st.st_size); git_str_dispose(&target_path); #endif } void test_link__stat_hardlink(void) { struct stat st; if (!should_run()) clar__skip(); cl_git_rewritefile("stat_hardlink1", "This file has many names!\n"); do_hardlink("stat_hardlink1", "stat_hardlink2"); cl_must_pass(p_stat("stat_hardlink1", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(26, st.st_size); cl_must_pass(p_stat("stat_hardlink2", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(26, st.st_size); } void test_link__lstat_hardlink(void) { struct stat st; if (!should_run()) clar__skip(); cl_git_rewritefile("lstat_hardlink1", "This file has many names!\n"); do_hardlink("lstat_hardlink1", "lstat_hardlink2"); cl_must_pass(p_lstat("lstat_hardlink1", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(26, st.st_size); cl_must_pass(p_lstat("lstat_hardlink2", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(26, st.st_size); } void test_link__stat_reparse_point(void) { #ifdef GIT_WIN32 struct stat st; /* Generic reparse points should be treated as regular files, only * symlinks and junctions should be treated as links. */ cl_git_rewritefile("stat_reparse", "This is a reparse point!\n"); do_custom_reparse("stat_reparse"); cl_must_pass(p_lstat("stat_reparse", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(25, st.st_size); #endif } void test_link__lstat_reparse_point(void) { #ifdef GIT_WIN32 struct stat st; cl_git_rewritefile("lstat_reparse", "This is a reparse point!\n"); do_custom_reparse("lstat_reparse"); cl_must_pass(p_lstat("lstat_reparse", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_equal_i(25, st.st_size); #endif } void test_link__readlink_nonexistent_file(void) { char buf[2048]; cl_must_fail(p_readlink("readlink_nonexistent", buf, 2048)); cl_assert_equal_i(ENOENT, errno); } void test_link__readlink_normal_file(void) { char buf[2048]; cl_git_rewritefile("readlink_regfile", "This is a regular file!\n"); cl_must_fail(p_readlink("readlink_regfile", buf, 2048)); cl_assert_equal_i(EINVAL, errno); } void test_link__readlink_symlink(void) { git_str target_path = GIT_STR_INIT; int len; char buf[2048]; if (!should_run()) clar__skip(); git_str_join(&target_path, '/', clar_sandbox_path(), "readlink_target"); cl_git_rewritefile("readlink_target", "This is the target of a symlink\n"); do_symlink(git_str_cstr(&target_path), "readlink_link", 0); len = p_readlink("readlink_link", buf, 2048); cl_must_pass(len); buf[len] = 0; cl_assert_equal_s(git_str_cstr(&target_path), buf); git_str_dispose(&target_path); } void test_link__readlink_dangling(void) { git_str target_path = GIT_STR_INIT; int len; char buf[2048]; if (!should_run()) clar__skip(); git_str_join(&target_path, '/', clar_sandbox_path(), "readlink_nonexistent"); do_symlink(git_str_cstr(&target_path), "readlink_dangling", 0); len = p_readlink("readlink_dangling", buf, 2048); cl_must_pass(len); buf[len] = 0; cl_assert_equal_s(git_str_cstr(&target_path), buf); git_str_dispose(&target_path); } void test_link__readlink_multiple(void) { git_str target_path = GIT_STR_INIT, path3 = GIT_STR_INIT, path2 = GIT_STR_INIT, path1 = GIT_STR_INIT; int len; char buf[2048]; if (!should_run()) clar__skip(); git_str_join(&target_path, '/', clar_sandbox_path(), "readlink_final"); git_str_join(&path3, '/', clar_sandbox_path(), "readlink_3"); git_str_join(&path2, '/', clar_sandbox_path(), "readlink_2"); git_str_join(&path1, '/', clar_sandbox_path(), "readlink_1"); do_symlink(git_str_cstr(&target_path), git_str_cstr(&path3), 0); do_symlink(git_str_cstr(&path3), git_str_cstr(&path2), 0); do_symlink(git_str_cstr(&path2), git_str_cstr(&path1), 0); len = p_readlink("readlink_1", buf, 2048); cl_must_pass(len); buf[len] = 0; cl_assert_equal_s(git_str_cstr(&path2), buf); git_str_dispose(&path1); git_str_dispose(&path2); git_str_dispose(&path3); git_str_dispose(&target_path); }
libgit2-main
tests/util/link.c
#include "clar_libgit2.h" static void assert_l32_parses(const char *string, int32_t expected, int base) { int32_t i; cl_git_pass(git__strntol32(&i, string, strlen(string), NULL, base)); cl_assert_equal_i(i, expected); } static void assert_l32_fails(const char *string, int base) { int32_t i; cl_git_fail(git__strntol32(&i, string, strlen(string), NULL, base)); } static void assert_l64_parses(const char *string, int64_t expected, int base) { int64_t i; cl_git_pass(git__strntol64(&i, string, strlen(string), NULL, base)); cl_assert_equal_i(i, expected); } static void assert_l64_fails(const char *string, int base) { int64_t i; cl_git_fail(git__strntol64(&i, string, strlen(string), NULL, base)); } void test_strtol__int32(void) { assert_l32_parses("123", 123, 10); assert_l32_parses(" +123 ", 123, 10); assert_l32_parses(" -123 ", -123, 10); assert_l32_parses(" +2147483647 ", 2147483647, 10); assert_l32_parses(" -2147483648 ", INT64_C(-2147483648), 10); assert_l32_parses("A", 10, 16); assert_l32_parses("1x1", 1, 10); assert_l32_fails("", 10); assert_l32_fails("a", 10); assert_l32_fails("x10x", 10); assert_l32_fails(" 2147483657 ", 10); assert_l32_fails(" -2147483657 ", 10); } void test_strtol__int64(void) { assert_l64_parses("123", 123, 10); assert_l64_parses(" +123 ", 123, 10); assert_l64_parses(" -123 ", -123, 10); assert_l64_parses(" +2147483647 ", 2147483647, 10); assert_l64_parses(" -2147483648 ", INT64_C(-2147483648), 10); assert_l64_parses(" 2147483657 ", INT64_C(2147483657), 10); assert_l64_parses(" -2147483657 ", INT64_C(-2147483657), 10); assert_l64_parses(" 9223372036854775807 ", INT64_MAX, 10); assert_l64_parses(" -9223372036854775808 ", INT64_MIN, 10); assert_l64_parses(" 0x7fffffffffffffff ", INT64_MAX, 16); assert_l64_parses(" -0x8000000000000000 ", INT64_MIN, 16); assert_l64_parses("1a", 26, 16); assert_l64_parses("1A", 26, 16); assert_l64_fails("", 10); assert_l64_fails("a", 10); assert_l64_fails("x10x", 10); assert_l64_fails("0x8000000000000000", 16); assert_l64_fails("-0x8000000000000001", 16); } void test_strtol__base_autodetection(void) { assert_l64_parses("0", 0, 0); assert_l64_parses("00", 0, 0); assert_l64_parses("0x", 0, 0); assert_l64_parses("0foobar", 0, 0); assert_l64_parses("07", 7, 0); assert_l64_parses("017", 15, 0); assert_l64_parses("0x8", 8, 0); assert_l64_parses("0x18", 24, 0); } void test_strtol__buffer_length_with_autodetection_truncates(void) { int64_t i64; cl_git_pass(git__strntol64(&i64, "011", 2, NULL, 0)); cl_assert_equal_i(i64, 1); cl_git_pass(git__strntol64(&i64, "0x11", 3, NULL, 0)); cl_assert_equal_i(i64, 1); } void test_strtol__buffer_length_truncates(void) { int32_t i32; int64_t i64; cl_git_pass(git__strntol32(&i32, "11", 1, NULL, 10)); cl_assert_equal_i(i32, 1); cl_git_pass(git__strntol64(&i64, "11", 1, NULL, 10)); cl_assert_equal_i(i64, 1); } void test_strtol__buffer_length_with_leading_ws_truncates(void) { int64_t i64; cl_git_fail(git__strntol64(&i64, " 1", 1, NULL, 10)); cl_git_pass(git__strntol64(&i64, " 11", 2, NULL, 10)); cl_assert_equal_i(i64, 1); } void test_strtol__buffer_length_with_leading_sign_truncates(void) { int64_t i64; cl_git_fail(git__strntol64(&i64, "-1", 1, NULL, 10)); cl_git_pass(git__strntol64(&i64, "-11", 2, NULL, 10)); cl_assert_equal_i(i64, -1); } void test_strtol__error_message_cuts_off(void) { assert_l32_fails("2147483657foobar", 10); cl_assert(strstr(git_error_last()->message, "2147483657") != NULL); cl_assert(strstr(git_error_last()->message, "foobar") == NULL); }
libgit2-main
tests/util/strtol.c
#include "clar_libgit2.h" void test_init__returns_count(void) { /* libgit2_tests initializes us first, so we have an existing * initialization. */ cl_assert_equal_i(2, git_libgit2_init()); cl_assert_equal_i(3, git_libgit2_init()); cl_assert_equal_i(2, git_libgit2_shutdown()); cl_assert_equal_i(1, git_libgit2_shutdown()); } void test_init__reinit_succeeds(void) { cl_assert_equal_i(0, git_libgit2_shutdown()); cl_assert_equal_i(1, git_libgit2_init()); cl_sandbox_set_search_path_defaults(); } #ifdef GIT_THREADS static void *reinit(void *unused) { unsigned i; for (i = 0; i < 20; i++) { cl_assert(git_libgit2_init() > 0); cl_assert(git_libgit2_shutdown() >= 0); } return unused; } #endif void test_init__concurrent_init_succeeds(void) { #ifdef GIT_THREADS git_thread threads[10]; unsigned i; cl_assert_equal_i(2, git_libgit2_init()); for (i = 0; i < ARRAY_SIZE(threads); i++) git_thread_create(&threads[i], reinit, NULL); for (i = 0; i < ARRAY_SIZE(threads); i++) git_thread_join(&threads[i], NULL); cl_assert_equal_i(1, git_libgit2_shutdown()); cl_sandbox_set_search_path_defaults(); #else cl_skip(); #endif }
libgit2-main
tests/util/init.c
#include <stdint.h> #include "clar_libgit2.h" #include "vector.h" /* initial size of 1 would cause writing past array bounds */ void test_vector__0(void) { git_vector x; int i; cl_git_pass(git_vector_init(&x, 1, NULL)); for (i = 0; i < 10; ++i) { git_vector_insert(&x, (void*) 0xabc); } git_vector_free(&x); } /* don't read past array bounds on remove() */ void test_vector__1(void) { git_vector x; /* make initial capacity exact for our insertions. */ cl_git_pass(git_vector_init(&x, 3, NULL)); git_vector_insert(&x, (void*) 0xabc); git_vector_insert(&x, (void*) 0xdef); git_vector_insert(&x, (void*) 0x123); git_vector_remove(&x, 0); /* used to read past array bounds. */ git_vector_free(&x); } static int test_cmp(const void *a, const void *b) { return *(const int *)a - *(const int *)b; } /* remove duplicates */ void test_vector__2(void) { git_vector x; int *ptrs[2]; ptrs[0] = git__malloc(sizeof(int)); ptrs[1] = git__malloc(sizeof(int)); *ptrs[0] = 2; *ptrs[1] = 1; cl_git_pass(git_vector_init(&x, 5, test_cmp)); cl_git_pass(git_vector_insert(&x, ptrs[0])); cl_git_pass(git_vector_insert(&x, ptrs[1])); cl_git_pass(git_vector_insert(&x, ptrs[1])); cl_git_pass(git_vector_insert(&x, ptrs[0])); cl_git_pass(git_vector_insert(&x, ptrs[1])); cl_assert(x.length == 5); git_vector_uniq(&x, NULL); cl_assert(x.length == 2); git_vector_free(&x); git__free(ptrs[0]); git__free(ptrs[1]); } static int compare_them(const void *a, const void *b) { return (int)((intptr_t)a - (intptr_t)b); } /* insert_sorted */ void test_vector__3(void) { git_vector x; intptr_t i; cl_git_pass(git_vector_init(&x, 1, &compare_them)); for (i = 0; i < 10; i += 2) { git_vector_insert_sorted(&x, (void*)(i + 1), NULL); } for (i = 9; i > 0; i -= 2) { git_vector_insert_sorted(&x, (void*)(i + 1), NULL); } cl_assert(x.length == 10); for (i = 0; i < 10; ++i) { cl_assert(git_vector_get(&x, i) == (void*)(i + 1)); } git_vector_free(&x); } /* insert_sorted with duplicates */ void test_vector__4(void) { git_vector x; intptr_t i; cl_git_pass(git_vector_init(&x, 1, &compare_them)); for (i = 0; i < 10; i += 2) { git_vector_insert_sorted(&x, (void*)(i + 1), NULL); } for (i = 9; i > 0; i -= 2) { git_vector_insert_sorted(&x, (void*)(i + 1), NULL); } for (i = 0; i < 10; i += 2) { git_vector_insert_sorted(&x, (void*)(i + 1), NULL); } for (i = 9; i > 0; i -= 2) { git_vector_insert_sorted(&x, (void*)(i + 1), NULL); } cl_assert(x.length == 20); for (i = 0; i < 20; ++i) { cl_assert(git_vector_get(&x, i) == (void*)(i / 2 + 1)); } git_vector_free(&x); } typedef struct { int content; int count; } my_struct; static int _struct_count = 0; static int compare_structs(const void *a, const void *b) { return ((const my_struct *)a)->content - ((const my_struct *)b)->content; } static int merge_structs(void **old_raw, void *new) { my_struct *old = *(my_struct **)old_raw; cl_assert(((my_struct *)old)->content == ((my_struct *)new)->content); ((my_struct *)old)->count += 1; git__free(new); _struct_count--; return GIT_EEXISTS; } static my_struct *alloc_struct(int value) { my_struct *st = git__malloc(sizeof(my_struct)); st->content = value; st->count = 0; _struct_count++; return st; } /* insert_sorted with duplicates and special handling */ void test_vector__5(void) { git_vector x; int i; cl_git_pass(git_vector_init(&x, 1, &compare_structs)); for (i = 0; i < 10; i += 2) git_vector_insert_sorted(&x, alloc_struct(i), &merge_structs); for (i = 9; i > 0; i -= 2) git_vector_insert_sorted(&x, alloc_struct(i), &merge_structs); cl_assert(x.length == 10); cl_assert(_struct_count == 10); for (i = 0; i < 10; i += 2) git_vector_insert_sorted(&x, alloc_struct(i), &merge_structs); for (i = 9; i > 0; i -= 2) git_vector_insert_sorted(&x, alloc_struct(i), &merge_structs); cl_assert(x.length == 10); cl_assert(_struct_count == 10); for (i = 0; i < 10; ++i) { cl_assert(((my_struct *)git_vector_get(&x, i))->content == i); git__free(git_vector_get(&x, i)); _struct_count--; } git_vector_free(&x); } static int remove_ones(const git_vector *v, size_t idx, void *p) { GIT_UNUSED(p); return (git_vector_get(v, idx) == (void *)0x001); } /* Test removal based on callback */ void test_vector__remove_matching(void) { git_vector x; size_t i; void *compare; cl_git_pass(git_vector_init(&x, 1, NULL)); git_vector_insert(&x, (void*) 0x001); cl_assert(x.length == 1); git_vector_remove_matching(&x, remove_ones, NULL); cl_assert(x.length == 0); git_vector_insert(&x, (void*) 0x001); git_vector_insert(&x, (void*) 0x001); git_vector_insert(&x, (void*) 0x001); cl_assert(x.length == 3); git_vector_remove_matching(&x, remove_ones, NULL); cl_assert(x.length == 0); git_vector_insert(&x, (void*) 0x002); git_vector_insert(&x, (void*) 0x001); git_vector_insert(&x, (void*) 0x002); git_vector_insert(&x, (void*) 0x001); cl_assert(x.length == 4); git_vector_remove_matching(&x, remove_ones, NULL); cl_assert(x.length == 2); git_vector_foreach(&x, i, compare) { cl_assert(compare != (void *)0x001); } git_vector_clear(&x); git_vector_insert(&x, (void*) 0x001); git_vector_insert(&x, (void*) 0x002); git_vector_insert(&x, (void*) 0x002); git_vector_insert(&x, (void*) 0x001); cl_assert(x.length == 4); git_vector_remove_matching(&x, remove_ones, NULL); cl_assert(x.length == 2); git_vector_foreach(&x, i, compare) { cl_assert(compare != (void *)0x001); } git_vector_clear(&x); git_vector_insert(&x, (void*) 0x002); git_vector_insert(&x, (void*) 0x001); git_vector_insert(&x, (void*) 0x002); git_vector_insert(&x, (void*) 0x001); cl_assert(x.length == 4); git_vector_remove_matching(&x, remove_ones, NULL); cl_assert(x.length == 2); git_vector_foreach(&x, i, compare) { cl_assert(compare != (void *)0x001); } git_vector_clear(&x); git_vector_insert(&x, (void*) 0x002); git_vector_insert(&x, (void*) 0x003); git_vector_insert(&x, (void*) 0x002); git_vector_insert(&x, (void*) 0x003); cl_assert(x.length == 4); git_vector_remove_matching(&x, remove_ones, NULL); cl_assert(x.length == 4); git_vector_free(&x); } static void assert_vector(git_vector *x, void *expected[], size_t len) { size_t i; cl_assert_equal_i(len, x->length); for (i = 0; i < len; i++) cl_assert(expected[i] == x->contents[i]); } void test_vector__grow_and_shrink(void) { git_vector x = GIT_VECTOR_INIT; void *expected1[] = { (void *)0x02, (void *)0x03, (void *)0x04, (void *)0x05, (void *)0x06, (void *)0x07, (void *)0x08, (void *)0x09, (void *)0x0a }; void *expected2[] = { (void *)0x02, (void *)0x04, (void *)0x05, (void *)0x06, (void *)0x07, (void *)0x08, (void *)0x09, (void *)0x0a }; void *expected3[] = { (void *)0x02, (void *)0x04, (void *)0x05, (void *)0x06, (void *)0x0a }; void *expected4[] = { (void *)0x02, (void *)0x04, (void *)0x05 }; void *expected5[] = { (void *)0x00, (void *)0x00, (void *)0x02, (void *)0x04, (void *)0x05 }; void *expected6[] = { (void *)0x00, (void *)0x00, (void *)0x02, (void *)0x04, (void *)0x05, (void *)0x00 }; void *expected7[] = { (void *)0x00, (void *)0x00, (void *)0x02, (void *)0x04, (void *)0x00, (void *)0x00, (void *)0x00, (void *)0x05, (void *)0x00 }; void *expected8[] = { (void *)0x04, (void *)0x00, (void *)0x00, (void *)0x00, (void *)0x05, (void *)0x00 }; void *expected9[] = { (void *)0x04, (void *)0x00, (void *)0x05, (void *)0x00 }; void *expectedA[] = { (void *)0x04, (void *)0x00 }; void *expectedB[] = { (void *)0x04 }; git_vector_insert(&x, (void *)0x01); git_vector_insert(&x, (void *)0x02); git_vector_insert(&x, (void *)0x03); git_vector_insert(&x, (void *)0x04); git_vector_insert(&x, (void *)0x05); git_vector_insert(&x, (void *)0x06); git_vector_insert(&x, (void *)0x07); git_vector_insert(&x, (void *)0x08); git_vector_insert(&x, (void *)0x09); git_vector_insert(&x, (void *)0x0a); git_vector_remove_range(&x, 0, 1); assert_vector(&x, expected1, ARRAY_SIZE(expected1)); git_vector_remove_range(&x, 1, 1); assert_vector(&x, expected2, ARRAY_SIZE(expected2)); git_vector_remove_range(&x, 4, 3); assert_vector(&x, expected3, ARRAY_SIZE(expected3)); git_vector_remove_range(&x, 3, 2); assert_vector(&x, expected4, ARRAY_SIZE(expected4)); git_vector_insert_null(&x, 0, 2); assert_vector(&x, expected5, ARRAY_SIZE(expected5)); git_vector_insert_null(&x, 5, 1); assert_vector(&x, expected6, ARRAY_SIZE(expected6)); git_vector_insert_null(&x, 4, 3); assert_vector(&x, expected7, ARRAY_SIZE(expected7)); git_vector_remove_range(&x, 0, 3); assert_vector(&x, expected8, ARRAY_SIZE(expected8)); git_vector_remove_range(&x, 1, 2); assert_vector(&x, expected9, ARRAY_SIZE(expected9)); git_vector_remove_range(&x, 2, 2); assert_vector(&x, expectedA, ARRAY_SIZE(expectedA)); git_vector_remove_range(&x, 1, 1); assert_vector(&x, expectedB, ARRAY_SIZE(expectedB)); git_vector_remove_range(&x, 0, 1); assert_vector(&x, NULL, 0); git_vector_free(&x); } void test_vector__reverse(void) { git_vector v = GIT_VECTOR_INIT; size_t i; void *in1[] = {(void *) 0x0, (void *) 0x1, (void *) 0x2, (void *) 0x3}; void *out1[] = {(void *) 0x3, (void *) 0x2, (void *) 0x1, (void *) 0x0}; void *in2[] = {(void *) 0x0, (void *) 0x1, (void *) 0x2, (void *) 0x3, (void *) 0x4}; void *out2[] = {(void *) 0x4, (void *) 0x3, (void *) 0x2, (void *) 0x1, (void *) 0x0}; for (i = 0; i < 4; i++) cl_git_pass(git_vector_insert(&v, in1[i])); git_vector_reverse(&v); for (i = 0; i < 4; i++) cl_assert_equal_p(out1[i], git_vector_get(&v, i)); git_vector_clear(&v); for (i = 0; i < 5; i++) cl_git_pass(git_vector_insert(&v, in2[i])); git_vector_reverse(&v); for (i = 0; i < 5; i++) cl_assert_equal_p(out2[i], git_vector_get(&v, i)); git_vector_free(&v); } void test_vector__dup_empty_vector(void) { git_vector v = GIT_VECTOR_INIT; git_vector dup = GIT_VECTOR_INIT; int dummy; cl_assert_equal_i(0, v.length); cl_git_pass(git_vector_dup(&dup, &v, v._cmp)); cl_assert_equal_i(0, dup._alloc_size); cl_assert_equal_i(0, dup.length); cl_git_pass(git_vector_insert(&dup, &dummy)); cl_assert_equal_i(8, dup._alloc_size); cl_assert_equal_i(1, dup.length); git_vector_free(&dup); }
libgit2-main
tests/util/vector.c
#include "clar_libgit2.h" #include "futils.h" #define TESTSTR "Have you seen that? Have you seeeen that??" const char *test_string = TESTSTR; const char *test_string_x2 = TESTSTR TESTSTR; #define TESTSTR_4096 REP1024("1234") #define TESTSTR_8192 REP1024("12341234") const char *test_4096 = TESTSTR_4096; const char *test_8192 = TESTSTR_8192; /* test basic data concatenation */ void test_gitstr__0(void) { git_str buf = GIT_STR_INIT; cl_assert(buf.size == 0); git_str_puts(&buf, test_string); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(test_string, git_str_cstr(&buf)); git_str_puts(&buf, test_string); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(test_string_x2, git_str_cstr(&buf)); git_str_dispose(&buf); } /* test git_str_printf */ void test_gitstr__1(void) { git_str buf = GIT_STR_INIT; git_str_printf(&buf, "%s %s %d ", "shoop", "da", 23); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s("shoop da 23 ", git_str_cstr(&buf)); git_str_printf(&buf, "%s %d", "woop", 42); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s("shoop da 23 woop 42", git_str_cstr(&buf)); git_str_dispose(&buf); } /* more thorough test of concatenation options */ void test_gitstr__2(void) { git_str buf = GIT_STR_INIT; int i; char data[128]; cl_assert(buf.size == 0); /* this must be safe to do */ git_str_dispose(&buf); cl_assert(buf.size == 0); cl_assert(buf.asize == 0); /* empty buffer should be empty string */ cl_assert_equal_s("", git_str_cstr(&buf)); cl_assert(buf.size == 0); /* cl_assert(buf.asize == 0); -- should not assume what git_str does */ /* free should set us back to the beginning */ git_str_dispose(&buf); cl_assert(buf.size == 0); cl_assert(buf.asize == 0); /* add letter */ git_str_putc(&buf, '+'); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s("+", git_str_cstr(&buf)); /* add letter again */ git_str_putc(&buf, '+'); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s("++", git_str_cstr(&buf)); /* let's try that a few times */ for (i = 0; i < 16; ++i) { git_str_putc(&buf, '+'); cl_assert(git_str_oom(&buf) == 0); } cl_assert_equal_s("++++++++++++++++++", git_str_cstr(&buf)); git_str_dispose(&buf); /* add data */ git_str_put(&buf, "xo", 2); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s("xo", git_str_cstr(&buf)); /* add letter again */ git_str_put(&buf, "xo", 2); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s("xoxo", git_str_cstr(&buf)); /* let's try that a few times */ for (i = 0; i < 16; ++i) { git_str_put(&buf, "xo", 2); cl_assert(git_str_oom(&buf) == 0); } cl_assert_equal_s("xoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxoxo", git_str_cstr(&buf)); git_str_dispose(&buf); /* set to string */ git_str_sets(&buf, test_string); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(test_string, git_str_cstr(&buf)); /* append string */ git_str_puts(&buf, test_string); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(test_string_x2, git_str_cstr(&buf)); /* set to string again (should overwrite - not append) */ git_str_sets(&buf, test_string); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(test_string, git_str_cstr(&buf)); /* test clear */ git_str_clear(&buf); cl_assert_equal_s("", git_str_cstr(&buf)); git_str_dispose(&buf); /* test extracting data into buffer */ git_str_puts(&buf, REP4("0123456789")); cl_assert(git_str_oom(&buf) == 0); git_str_copy_cstr(data, sizeof(data), &buf); cl_assert_equal_s(REP4("0123456789"), data); git_str_copy_cstr(data, 11, &buf); cl_assert_equal_s("0123456789", data); git_str_copy_cstr(data, 3, &buf); cl_assert_equal_s("01", data); git_str_copy_cstr(data, 1, &buf); cl_assert_equal_s("", data); git_str_copy_cstr(data, sizeof(data), &buf); cl_assert_equal_s(REP4("0123456789"), data); git_str_sets(&buf, REP256("x")); git_str_copy_cstr(data, sizeof(data), &buf); /* since sizeof(data) == 128, only 127 bytes should be copied */ cl_assert_equal_s(REP4(REP16("x")) REP16("x") REP16("x") REP16("x") "xxxxxxxxxxxxxxx", data); git_str_dispose(&buf); git_str_copy_cstr(data, sizeof(data), &buf); cl_assert_equal_s("", data); } /* let's do some tests with larger buffers to push our limits */ void test_gitstr__3(void) { git_str buf = GIT_STR_INIT; /* set to string */ git_str_set(&buf, test_4096, 4096); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(test_4096, git_str_cstr(&buf)); /* append string */ git_str_puts(&buf, test_4096); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(test_8192, git_str_cstr(&buf)); /* set to string again (should overwrite - not append) */ git_str_set(&buf, test_4096, 4096); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(test_4096, git_str_cstr(&buf)); git_str_dispose(&buf); } /* let's try some producer/consumer tests */ void test_gitstr__4(void) { git_str buf = GIT_STR_INIT; int i; for (i = 0; i < 10; ++i) { git_str_puts(&buf, "1234"); /* add 4 */ cl_assert(git_str_oom(&buf) == 0); git_str_consume(&buf, buf.ptr + 2); /* eat the first two */ cl_assert(strlen(git_str_cstr(&buf)) == (size_t)((i + 1) * 2)); } /* we have appended 1234 10x and removed the first 20 letters */ cl_assert_equal_s("12341234123412341234", git_str_cstr(&buf)); git_str_consume(&buf, NULL); cl_assert_equal_s("12341234123412341234", git_str_cstr(&buf)); git_str_consume(&buf, "invalid pointer"); cl_assert_equal_s("12341234123412341234", git_str_cstr(&buf)); git_str_consume(&buf, buf.ptr); cl_assert_equal_s("12341234123412341234", git_str_cstr(&buf)); git_str_consume(&buf, buf.ptr + 1); cl_assert_equal_s("2341234123412341234", git_str_cstr(&buf)); git_str_consume(&buf, buf.ptr + buf.size); cl_assert_equal_s("", git_str_cstr(&buf)); git_str_dispose(&buf); } static void check_buf_append( const char* data_a, const char* data_b, const char* expected_data, size_t expected_size, size_t expected_asize) { git_str tgt = GIT_STR_INIT; git_str_sets(&tgt, data_a); cl_assert(git_str_oom(&tgt) == 0); git_str_puts(&tgt, data_b); cl_assert(git_str_oom(&tgt) == 0); cl_assert_equal_s(expected_data, git_str_cstr(&tgt)); cl_assert_equal_i(tgt.size, expected_size); if (expected_asize > 0) cl_assert_equal_i(tgt.asize, expected_asize); git_str_dispose(&tgt); } static void check_buf_append_abc( const char* buf_a, const char* buf_b, const char* buf_c, const char* expected_ab, const char* expected_abc, const char* expected_abca, const char* expected_abcab, const char* expected_abcabc) { git_str buf = GIT_STR_INIT; git_str_sets(&buf, buf_a); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(buf_a, git_str_cstr(&buf)); git_str_puts(&buf, buf_b); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(expected_ab, git_str_cstr(&buf)); git_str_puts(&buf, buf_c); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(expected_abc, git_str_cstr(&buf)); git_str_puts(&buf, buf_a); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(expected_abca, git_str_cstr(&buf)); git_str_puts(&buf, buf_b); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(expected_abcab, git_str_cstr(&buf)); git_str_puts(&buf, buf_c); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(expected_abcabc, git_str_cstr(&buf)); git_str_dispose(&buf); } /* more variations on append tests */ void test_gitstr__5(void) { check_buf_append("", "", "", 0, 0); check_buf_append("a", "", "a", 1, 0); check_buf_append("", "a", "a", 1, 8); check_buf_append("", "a", "a", 1, 8); check_buf_append("a", "b", "ab", 2, 8); check_buf_append("", "abcdefgh", "abcdefgh", 8, 16); check_buf_append("abcdefgh", "", "abcdefgh", 8, 16); /* buffer with starting asize will grow to: * 1 -> 2, 2 -> 3, 3 -> 5, 4 -> 6, 5 -> 8, 6 -> 9, * 7 -> 11, 8 -> 12, 9 -> 14, 10 -> 15, 11 -> 17, 12 -> 18, * 13 -> 20, 14 -> 21, 15 -> 23, 16 -> 24, 17 -> 26, 18 -> 27, * 19 -> 29, 20 -> 30, 21 -> 32, 22 -> 33, 23 -> 35, 24 -> 36, * ... * follow sequence until value > target size, * then round up to nearest multiple of 8. */ check_buf_append("abcdefgh", "/", "abcdefgh/", 9, 16); check_buf_append("abcdefgh", "ijklmno", "abcdefghijklmno", 15, 16); check_buf_append("abcdefgh", "ijklmnop", "abcdefghijklmnop", 16, 24); check_buf_append("0123456789", "0123456789", "01234567890123456789", 20, 24); check_buf_append(REP16("x"), REP16("o"), REP16("x") REP16("o"), 32, 40); check_buf_append(test_4096, "", test_4096, 4096, 4104); check_buf_append(test_4096, test_4096, test_8192, 8192, 8200); /* check sequences of appends */ check_buf_append_abc("a", "b", "c", "ab", "abc", "abca", "abcab", "abcabc"); check_buf_append_abc("a1", "b2", "c3", "a1b2", "a1b2c3", "a1b2c3a1", "a1b2c3a1b2", "a1b2c3a1b2c3"); check_buf_append_abc("a1/", "b2/", "c3/", "a1/b2/", "a1/b2/c3/", "a1/b2/c3/a1/", "a1/b2/c3/a1/b2/", "a1/b2/c3/a1/b2/c3/"); } /* test swap */ void test_gitstr__6(void) { git_str a = GIT_STR_INIT; git_str b = GIT_STR_INIT; git_str_sets(&a, "foo"); cl_assert(git_str_oom(&a) == 0); git_str_sets(&b, "bar"); cl_assert(git_str_oom(&b) == 0); cl_assert_equal_s("foo", git_str_cstr(&a)); cl_assert_equal_s("bar", git_str_cstr(&b)); git_str_swap(&a, &b); cl_assert_equal_s("bar", git_str_cstr(&a)); cl_assert_equal_s("foo", git_str_cstr(&b)); git_str_dispose(&a); git_str_dispose(&b); } /* test detach/attach data */ void test_gitstr__7(void) { const char *fun = "This is fun"; git_str a = GIT_STR_INIT; char *b = NULL; git_str_sets(&a, "foo"); cl_assert(git_str_oom(&a) == 0); cl_assert_equal_s("foo", git_str_cstr(&a)); b = git_str_detach(&a); cl_assert_equal_s("foo", b); cl_assert_equal_s("", a.ptr); git__free(b); b = git_str_detach(&a); cl_assert_equal_s(NULL, b); cl_assert_equal_s("", a.ptr); git_str_dispose(&a); b = git__strdup(fun); git_str_attach(&a, b, 0); cl_assert_equal_s(fun, a.ptr); cl_assert(a.size == strlen(fun)); cl_assert(a.asize == strlen(fun) + 1); git_str_dispose(&a); b = git__strdup(fun); git_str_attach(&a, b, strlen(fun) + 1); cl_assert_equal_s(fun, a.ptr); cl_assert(a.size == strlen(fun)); cl_assert(a.asize == strlen(fun) + 1); git_str_dispose(&a); } static void check_joinbuf_2( const char *a, const char *b, const char *expected) { char sep = '/'; git_str buf = GIT_STR_INIT; git_str_join(&buf, sep, a, b); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(expected, git_str_cstr(&buf)); git_str_dispose(&buf); } static void check_joinbuf_overlapped( const char *oldval, int ofs_a, const char *b, const char *expected) { char sep = '/'; git_str buf = GIT_STR_INIT; git_str_sets(&buf, oldval); git_str_join(&buf, sep, buf.ptr + ofs_a, b); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(expected, git_str_cstr(&buf)); git_str_dispose(&buf); } static void check_joinbuf_n_2( const char *a, const char *b, const char *expected) { char sep = '/'; git_str buf = GIT_STR_INIT; git_str_sets(&buf, a); cl_assert(git_str_oom(&buf) == 0); git_str_join_n(&buf, sep, 1, b); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(expected, git_str_cstr(&buf)); git_str_dispose(&buf); } static void check_joinbuf_n_4( const char *a, const char *b, const char *c, const char *d, const char *expected) { char sep = ';'; git_str buf = GIT_STR_INIT; git_str_join_n(&buf, sep, 4, a, b, c, d); cl_assert(git_str_oom(&buf) == 0); cl_assert_equal_s(expected, git_str_cstr(&buf)); git_str_dispose(&buf); } /* test join */ void test_gitstr__8(void) { git_str a = GIT_STR_INIT; git_str_join_n(&a, '/', 1, "foo"); cl_assert(git_str_oom(&a) == 0); cl_assert_equal_s("foo", git_str_cstr(&a)); git_str_join_n(&a, '/', 1, "bar"); cl_assert(git_str_oom(&a) == 0); cl_assert_equal_s("foo/bar", git_str_cstr(&a)); git_str_join_n(&a, '/', 1, "baz"); cl_assert(git_str_oom(&a) == 0); cl_assert_equal_s("foo/bar/baz", git_str_cstr(&a)); git_str_dispose(&a); check_joinbuf_2(NULL, "", ""); check_joinbuf_2(NULL, "a", "a"); check_joinbuf_2(NULL, "/a", "/a"); check_joinbuf_2("", "", ""); check_joinbuf_2("", "a", "a"); check_joinbuf_2("", "/a", "/a"); check_joinbuf_2("a", "", "a/"); check_joinbuf_2("a", "/", "a/"); check_joinbuf_2("a", "b", "a/b"); check_joinbuf_2("/", "a", "/a"); check_joinbuf_2("/", "", "/"); check_joinbuf_2("/a", "/b", "/a/b"); check_joinbuf_2("/a", "/b/", "/a/b/"); check_joinbuf_2("/a/", "b/", "/a/b/"); check_joinbuf_2("/a/", "/b/", "/a/b/"); check_joinbuf_2("/a/", "//b/", "/a/b/"); check_joinbuf_2("/abcd", "/defg", "/abcd/defg"); check_joinbuf_2("/abcd", "/defg/", "/abcd/defg/"); check_joinbuf_2("/abcd/", "defg/", "/abcd/defg/"); check_joinbuf_2("/abcd/", "/defg/", "/abcd/defg/"); check_joinbuf_overlapped("abcd", 0, "efg", "abcd/efg"); check_joinbuf_overlapped("abcd", 1, "efg", "bcd/efg"); check_joinbuf_overlapped("abcd", 2, "efg", "cd/efg"); check_joinbuf_overlapped("abcd", 3, "efg", "d/efg"); check_joinbuf_overlapped("abcd", 4, "efg", "efg"); check_joinbuf_overlapped("abc/", 2, "efg", "c/efg"); check_joinbuf_overlapped("abc/", 3, "efg", "/efg"); check_joinbuf_overlapped("abc/", 4, "efg", "efg"); check_joinbuf_overlapped("abcd", 3, "", "d/"); check_joinbuf_overlapped("abcd", 4, "", ""); check_joinbuf_overlapped("abc/", 2, "", "c/"); check_joinbuf_overlapped("abc/", 3, "", "/"); check_joinbuf_overlapped("abc/", 4, "", ""); check_joinbuf_n_2("", "", ""); check_joinbuf_n_2("", "a", "a"); check_joinbuf_n_2("", "/a", "/a"); check_joinbuf_n_2("a", "", "a/"); check_joinbuf_n_2("a", "/", "a/"); check_joinbuf_n_2("a", "b", "a/b"); check_joinbuf_n_2("/", "a", "/a"); check_joinbuf_n_2("/", "", "/"); check_joinbuf_n_2("/a", "/b", "/a/b"); check_joinbuf_n_2("/a", "/b/", "/a/b/"); check_joinbuf_n_2("/a/", "b/", "/a/b/"); check_joinbuf_n_2("/a/", "/b/", "/a/b/"); check_joinbuf_n_2("/abcd", "/defg", "/abcd/defg"); check_joinbuf_n_2("/abcd", "/defg/", "/abcd/defg/"); check_joinbuf_n_2("/abcd/", "defg/", "/abcd/defg/"); check_joinbuf_n_2("/abcd/", "/defg/", "/abcd/defg/"); check_joinbuf_n_4("", "", "", "", ""); check_joinbuf_n_4("", "a", "", "", "a;"); check_joinbuf_n_4("a", "", "", "", "a;"); check_joinbuf_n_4("", "", "", "a", "a"); check_joinbuf_n_4("a", "b", "", ";c;d;", "a;b;c;d;"); check_joinbuf_n_4("a", "b", "", ";c;d", "a;b;c;d"); check_joinbuf_n_4("abcd", "efgh", "ijkl", "mnop", "abcd;efgh;ijkl;mnop"); check_joinbuf_n_4("abcd;", "efgh;", "ijkl;", "mnop;", "abcd;efgh;ijkl;mnop;"); check_joinbuf_n_4(";abcd;", ";efgh;", ";ijkl;", ";mnop;", ";abcd;efgh;ijkl;mnop;"); } void test_gitstr__9(void) { git_str buf = GIT_STR_INIT; /* just some exhaustive tests of various separator placement */ char *a[] = { "", "-", "a-", "-a", "-a-" }; char *b[] = { "", "-", "b-", "-b", "-b-" }; char sep[] = { 0, '-', '/' }; char *expect_null[] = { "", "-", "a-", "-a", "-a-", "-", "--", "a--", "-a-", "-a--", "b-", "-b-", "a-b-", "-ab-", "-a-b-", "-b", "--b", "a--b", "-a-b", "-a--b", "-b-", "--b-", "a--b-", "-a-b-", "-a--b-" }; char *expect_dash[] = { "", "-", "a-", "-a-", "-a-", "-", "-", "a-", "-a-", "-a-", "b-", "-b-", "a-b-", "-a-b-", "-a-b-", "-b", "-b", "a-b", "-a-b", "-a-b", "-b-", "-b-", "a-b-", "-a-b-", "-a-b-" }; char *expect_slas[] = { "", "-/", "a-/", "-a/", "-a-/", "-", "-/-", "a-/-", "-a/-", "-a-/-", "b-", "-/b-", "a-/b-", "-a/b-", "-a-/b-", "-b", "-/-b", "a-/-b", "-a/-b", "-a-/-b", "-b-", "-/-b-", "a-/-b-", "-a/-b-", "-a-/-b-" }; char **expect_values[] = { expect_null, expect_dash, expect_slas }; char separator, **expect; unsigned int s, i, j; for (s = 0; s < sizeof(sep) / sizeof(char); ++s) { separator = sep[s]; expect = expect_values[s]; for (j = 0; j < sizeof(b) / sizeof(char*); ++j) { for (i = 0; i < sizeof(a) / sizeof(char*); ++i) { git_str_join(&buf, separator, a[i], b[j]); cl_assert_equal_s(*expect, buf.ptr); expect++; } } } git_str_dispose(&buf); } void test_gitstr__10(void) { git_str a = GIT_STR_INIT; cl_git_pass(git_str_join_n(&a, '/', 1, "test")); cl_assert_equal_s(a.ptr, "test"); cl_git_pass(git_str_join_n(&a, '/', 1, "string")); cl_assert_equal_s(a.ptr, "test/string"); git_str_clear(&a); cl_git_pass(git_str_join_n(&a, '/', 3, "test", "string", "join")); cl_assert_equal_s(a.ptr, "test/string/join"); cl_git_pass(git_str_join_n(&a, '/', 2, a.ptr, "more")); cl_assert_equal_s(a.ptr, "test/string/join/test/string/join/more"); git_str_dispose(&a); } void test_gitstr__join3(void) { git_str a = GIT_STR_INIT; cl_git_pass(git_str_join3(&a, '/', "test", "string", "join")); cl_assert_equal_s("test/string/join", a.ptr); cl_git_pass(git_str_join3(&a, '/', "test/", "string", "join")); cl_assert_equal_s("test/string/join", a.ptr); cl_git_pass(git_str_join3(&a, '/', "test/", "/string", "join")); cl_assert_equal_s("test/string/join", a.ptr); cl_git_pass(git_str_join3(&a, '/', "test/", "/string/", "join")); cl_assert_equal_s("test/string/join", a.ptr); cl_git_pass(git_str_join3(&a, '/', "test/", "/string/", "/join")); cl_assert_equal_s("test/string/join", a.ptr); cl_git_pass(git_str_join3(&a, '/', "", "string", "join")); cl_assert_equal_s("string/join", a.ptr); cl_git_pass(git_str_join3(&a, '/', "", "string/", "join")); cl_assert_equal_s("string/join", a.ptr); cl_git_pass(git_str_join3(&a, '/', "", "string/", "/join")); cl_assert_equal_s("string/join", a.ptr); cl_git_pass(git_str_join3(&a, '/', "string", "", "join")); cl_assert_equal_s("string/join", a.ptr); cl_git_pass(git_str_join3(&a, '/', "string/", "", "join")); cl_assert_equal_s("string/join", a.ptr); cl_git_pass(git_str_join3(&a, '/', "string/", "", "/join")); cl_assert_equal_s("string/join", a.ptr); git_str_dispose(&a); } void test_gitstr__11(void) { git_str a = GIT_STR_INIT; char *t1[] = { "nothing", "in", "common" }; char *t2[] = { "something", "something else", "some other" }; char *t3[] = { "something", "some fun", "no fun" }; char *t4[] = { "happy", "happier", "happiest" }; char *t5[] = { "happiest", "happier", "happy" }; char *t6[] = { "no", "nope", "" }; char *t7[] = { "", "doesn't matter" }; cl_git_pass(git_str_common_prefix(&a, t1, 3)); cl_assert_equal_s(a.ptr, ""); cl_git_pass(git_str_common_prefix(&a, t2, 3)); cl_assert_equal_s(a.ptr, "some"); cl_git_pass(git_str_common_prefix(&a, t3, 3)); cl_assert_equal_s(a.ptr, ""); cl_git_pass(git_str_common_prefix(&a, t4, 3)); cl_assert_equal_s(a.ptr, "happ"); cl_git_pass(git_str_common_prefix(&a, t5, 3)); cl_assert_equal_s(a.ptr, "happ"); cl_git_pass(git_str_common_prefix(&a, t6, 3)); cl_assert_equal_s(a.ptr, ""); cl_git_pass(git_str_common_prefix(&a, t7, 3)); cl_assert_equal_s(a.ptr, ""); git_str_dispose(&a); } void test_gitstr__rfind_variants(void) { git_str a = GIT_STR_INIT; ssize_t len; cl_git_pass(git_str_sets(&a, "/this/is/it/")); len = (ssize_t)git_str_len(&a); cl_assert(git_str_rfind(&a, '/') == len - 1); cl_assert(git_str_rfind_next(&a, '/') == len - 4); cl_assert(git_str_rfind(&a, 'i') == len - 3); cl_assert(git_str_rfind_next(&a, 'i') == len - 3); cl_assert(git_str_rfind(&a, 'h') == 2); cl_assert(git_str_rfind_next(&a, 'h') == 2); cl_assert(git_str_rfind(&a, 'q') == -1); cl_assert(git_str_rfind_next(&a, 'q') == -1); git_str_dispose(&a); } void test_gitstr__puts_escaped(void) { git_str a = GIT_STR_INIT; git_str_clear(&a); cl_git_pass(git_str_puts_escaped(&a, "this is a test", "", "")); cl_assert_equal_s("this is a test", a.ptr); git_str_clear(&a); cl_git_pass(git_str_puts_escaped(&a, "this is a test", "t", "\\")); cl_assert_equal_s("\\this is a \\tes\\t", a.ptr); git_str_clear(&a); cl_git_pass(git_str_puts_escaped(&a, "this is a test", "i ", "__")); cl_assert_equal_s("th__is__ __is__ a__ test", a.ptr); git_str_clear(&a); cl_git_pass(git_str_puts_escape_regex(&a, "^match\\s*[A-Z]+.*")); cl_assert_equal_s("\\^match\\\\s\\*\\[A-Z\\]\\+\\.\\*", a.ptr); git_str_dispose(&a); } static void assert_unescape(char *expected, char *to_unescape) { git_str buf = GIT_STR_INIT; cl_git_pass(git_str_sets(&buf, to_unescape)); git_str_unescape(&buf); cl_assert_equal_s(expected, buf.ptr); cl_assert_equal_sz(strlen(expected), buf.size); git_str_dispose(&buf); } void test_gitstr__unescape(void) { assert_unescape("Escaped\\", "Es\\ca\\ped\\"); assert_unescape("Es\\caped\\", "Es\\\\ca\\ped\\\\"); assert_unescape("\\", "\\"); assert_unescape("\\", "\\\\"); assert_unescape("", ""); } void test_gitstr__encode_base64(void) { git_str buf = GIT_STR_INIT; /* t h i s * 0x 74 68 69 73 * 0b 01110100 01101000 01101001 01110011 * 0b 011101 000110 100001 101001 011100 110000 * 0x 1d 06 21 29 1c 30 * d G h p c w */ cl_git_pass(git_str_encode_base64(&buf, "this", 4)); cl_assert_equal_s("dGhpcw==", buf.ptr); git_str_clear(&buf); cl_git_pass(git_str_encode_base64(&buf, "this!", 5)); cl_assert_equal_s("dGhpcyE=", buf.ptr); git_str_clear(&buf); cl_git_pass(git_str_encode_base64(&buf, "this!\n", 6)); cl_assert_equal_s("dGhpcyEK", buf.ptr); git_str_dispose(&buf); } void test_gitstr__decode_base64(void) { git_str buf = GIT_STR_INIT; cl_git_pass(git_str_decode_base64(&buf, "dGhpcw==", 8)); cl_assert_equal_s("this", buf.ptr); git_str_clear(&buf); cl_git_pass(git_str_decode_base64(&buf, "dGhpcyE=", 8)); cl_assert_equal_s("this!", buf.ptr); git_str_clear(&buf); cl_git_pass(git_str_decode_base64(&buf, "dGhpcyEK", 8)); cl_assert_equal_s("this!\n", buf.ptr); cl_git_fail(git_str_decode_base64(&buf, "This is not a valid base64 string!!!", 36)); cl_assert_equal_s("this!\n", buf.ptr); git_str_dispose(&buf); } void test_gitstr__encode_base85(void) { git_str buf = GIT_STR_INIT; cl_git_pass(git_str_encode_base85(&buf, "this", 4)); cl_assert_equal_s("bZBXF", buf.ptr); git_str_clear(&buf); cl_git_pass(git_str_encode_base85(&buf, "two rnds", 8)); cl_assert_equal_s("ba!tca&BaE", buf.ptr); git_str_clear(&buf); cl_git_pass(git_str_encode_base85(&buf, "this is base 85 encoded", strlen("this is base 85 encoded"))); cl_assert_equal_s("bZBXFAZc?TVqtS-AUHK3Wo~0{WMyOk", buf.ptr); git_str_clear(&buf); git_str_dispose(&buf); } void test_gitstr__decode_base85(void) { git_str buf = GIT_STR_INIT; cl_git_pass(git_str_decode_base85(&buf, "bZBXF", 5, 4)); cl_assert_equal_sz(4, buf.size); cl_assert_equal_s("this", buf.ptr); git_str_clear(&buf); cl_git_pass(git_str_decode_base85(&buf, "ba!tca&BaE", 10, 8)); cl_assert_equal_sz(8, buf.size); cl_assert_equal_s("two rnds", buf.ptr); git_str_clear(&buf); cl_git_pass(git_str_decode_base85(&buf, "bZBXFAZc?TVqtS-AUHK3Wo~0{WMyOk", 30, 23)); cl_assert_equal_sz(23, buf.size); cl_assert_equal_s("this is base 85 encoded", buf.ptr); git_str_clear(&buf); git_str_dispose(&buf); } void test_gitstr__decode_base85_fails_gracefully(void) { git_str buf = GIT_STR_INIT; git_str_puts(&buf, "foobar"); cl_git_fail(git_str_decode_base85(&buf, "invalid charsZZ", 15, 42)); cl_git_fail(git_str_decode_base85(&buf, "invalidchars__ ", 15, 42)); cl_git_fail(git_str_decode_base85(&buf, "overflowZZ~~~~~", 15, 42)); cl_git_fail(git_str_decode_base85(&buf, "truncated", 9, 42)); cl_assert_equal_sz(6, buf.size); cl_assert_equal_s("foobar", buf.ptr); git_str_dispose(&buf); } void test_gitstr__classify_with_utf8(void) { char *data0 = "Simple text\n"; size_t data0len = 12; char *data1 = "Is that UTF-8 data I see…\nYep!\n"; size_t data1len = 31; char *data2 = "Internal NUL!!!\000\n\nI see you!\n"; size_t data2len = 29; char *data3 = "\xef\xbb\xbfThis is UTF-8 with a BOM.\n"; size_t data3len = 20; git_str b; b.ptr = data0; b.size = b.asize = data0len; cl_assert(!git_str_is_binary(&b)); cl_assert(!git_str_contains_nul(&b)); b.ptr = data1; b.size = b.asize = data1len; cl_assert(!git_str_is_binary(&b)); cl_assert(!git_str_contains_nul(&b)); b.ptr = data2; b.size = b.asize = data2len; cl_assert(git_str_is_binary(&b)); cl_assert(git_str_contains_nul(&b)); b.ptr = data3; b.size = b.asize = data3len; cl_assert(!git_str_is_binary(&b)); cl_assert(!git_str_contains_nul(&b)); } #include "crlf.h" #define check_buf(expected,buf) do { \ cl_assert_equal_s(expected, buf.ptr); \ cl_assert_equal_sz(strlen(expected), buf.size); } while (0) void test_gitstr__lf_and_crlf_conversions(void) { git_str src = GIT_STR_INIT, tgt = GIT_STR_INIT; /* LF source */ git_str_sets(&src, "lf\nlf\nlf\nlf\n"); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf("lf\r\nlf\r\nlf\r\nlf\r\n", tgt); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf(src.ptr, tgt); git_str_sets(&src, "\nlf\nlf\nlf\nlf\nlf"); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf("\r\nlf\r\nlf\r\nlf\r\nlf\r\nlf", tgt); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf(src.ptr, tgt); /* CRLF source */ git_str_sets(&src, "crlf\r\ncrlf\r\ncrlf\r\ncrlf\r\n"); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf("crlf\r\ncrlf\r\ncrlf\r\ncrlf\r\n", tgt); git_str_sets(&src, "crlf\r\ncrlf\r\ncrlf\r\ncrlf\r\n"); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf("crlf\ncrlf\ncrlf\ncrlf\n", tgt); git_str_sets(&src, "\r\ncrlf\r\ncrlf\r\ncrlf\r\ncrlf\r\ncrlf"); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf("\r\ncrlf\r\ncrlf\r\ncrlf\r\ncrlf\r\ncrlf", tgt); git_str_sets(&src, "\r\ncrlf\r\ncrlf\r\ncrlf\r\ncrlf\r\ncrlf"); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf("\ncrlf\ncrlf\ncrlf\ncrlf\ncrlf", tgt); /* CRLF in LF text */ git_str_sets(&src, "\nlf\nlf\ncrlf\r\nlf\nlf\ncrlf\r\n"); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf("\r\nlf\r\nlf\r\ncrlf\r\nlf\r\nlf\r\ncrlf\r\n", tgt); git_str_sets(&src, "\nlf\nlf\ncrlf\r\nlf\nlf\ncrlf\r\n"); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf("\nlf\nlf\ncrlf\nlf\nlf\ncrlf\n", tgt); /* LF in CRLF text */ git_str_sets(&src, "\ncrlf\r\ncrlf\r\nlf\ncrlf\r\ncrlf"); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf("\r\ncrlf\r\ncrlf\r\nlf\r\ncrlf\r\ncrlf", tgt); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf("\ncrlf\ncrlf\nlf\ncrlf\ncrlf", tgt); /* bare CR test */ git_str_sets(&src, "\rcrlf\r\nlf\nlf\ncr\rcrlf\r\nlf\ncr\r"); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf("\rcrlf\r\nlf\r\nlf\r\ncr\rcrlf\r\nlf\r\ncr\r", tgt); git_str_sets(&src, "\rcrlf\r\nlf\nlf\ncr\rcrlf\r\nlf\ncr\r"); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf("\rcrlf\nlf\nlf\ncr\rcrlf\nlf\ncr\r", tgt); git_str_sets(&src, "\rcr\r"); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf(src.ptr, tgt); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf("\rcr\r", tgt); git_str_dispose(&src); git_str_dispose(&tgt); /* blob correspondence tests */ git_str_sets(&src, ALL_CRLF_TEXT_RAW); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf(ALL_CRLF_TEXT_AS_CRLF, tgt); git_str_sets(&src, ALL_CRLF_TEXT_RAW); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf(ALL_CRLF_TEXT_AS_LF, tgt); git_str_dispose(&src); git_str_dispose(&tgt); git_str_sets(&src, ALL_LF_TEXT_RAW); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf(ALL_LF_TEXT_AS_CRLF, tgt); git_str_sets(&src, ALL_LF_TEXT_RAW); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf(ALL_LF_TEXT_AS_LF, tgt); git_str_dispose(&src); git_str_dispose(&tgt); git_str_sets(&src, MORE_CRLF_TEXT_RAW); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf(MORE_CRLF_TEXT_AS_CRLF, tgt); git_str_sets(&src, MORE_CRLF_TEXT_RAW); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf(MORE_CRLF_TEXT_AS_LF, tgt); git_str_dispose(&src); git_str_dispose(&tgt); git_str_sets(&src, MORE_LF_TEXT_RAW); cl_git_pass(git_str_lf_to_crlf(&tgt, &src)); check_buf(MORE_LF_TEXT_AS_CRLF, tgt); git_str_sets(&src, MORE_LF_TEXT_RAW); cl_git_pass(git_str_crlf_to_lf(&tgt, &src)); check_buf(MORE_LF_TEXT_AS_LF, tgt); git_str_dispose(&src); git_str_dispose(&tgt); } void test_gitstr__dont_grow_borrowed(void) { const char *somestring = "blah blah"; git_str buf = GIT_STR_INIT; git_str_attach_notowned(&buf, somestring, strlen(somestring) + 1); cl_assert_equal_p(somestring, buf.ptr); cl_assert_equal_i(0, buf.asize); cl_assert_equal_i(strlen(somestring) + 1, buf.size); cl_git_fail_with(GIT_EINVALID, git_str_grow(&buf, 1024)); } void test_gitstr__dont_hit_infinite_loop_when_resizing(void) { git_str buf = GIT_STR_INIT; cl_git_pass(git_str_puts(&buf, "foobar")); /* * We do not care whether this succeeds or fails, which * would depend on platform-specific allocation * semantics. We only want to know that the function * actually returns. */ (void)git_str_try_grow(&buf, SIZE_MAX, true); git_str_dispose(&buf); } void test_gitstr__avoid_printing_into_oom_buffer(void) { git_str buf = GIT_STR_INIT; /* Emulate OOM situation with a previous allocation */ buf.asize = 8; buf.ptr = git_str__oom; /* * Print the same string again. As the buffer still has * an `asize` of 8 due to the previous print, * `ENSURE_SIZE` would not try to reallocate the array at * all. As it didn't explicitly check for `git_str__oom` * in earlier versions, this would've resulted in it * returning successfully and thus `git_str_puts` would * just print into the `git_str__oom` array. */ cl_git_fail(git_str_puts(&buf, "foobar")); }
libgit2-main
tests/util/gitstr.c
#include "clar_libgit2.h" #include "bitvec.h" #if 0 static void print_bitvec(git_bitvec *bv) { int b; if (!bv->length) { for (b = 63; b >= 0; --b) fprintf(stderr, "%d", (bv->u.bits & (1ul << b)) ? 1 : 0); } else { for (b = bv->length * 8; b >= 0; --b) fprintf(stderr, "%d", (bv->u.ptr[b >> 3] & (b & 0x0ff)) ? 1 : 0); } fprintf(stderr, "\n"); } #endif static void set_some_bits(git_bitvec *bv, size_t length) { size_t i; for (i = 0; i < length; ++i) { if (i % 3 == 0 || i % 7 == 0) git_bitvec_set(bv, i, true); } } static void check_some_bits(git_bitvec *bv, size_t length) { size_t i; for (i = 0; i < length; ++i) cl_assert_equal_b(i % 3 == 0 || i % 7 == 0, git_bitvec_get(bv, i)); } void test_bitvec__0(void) { git_bitvec bv; cl_git_pass(git_bitvec_init(&bv, 32)); set_some_bits(&bv, 16); check_some_bits(&bv, 16); git_bitvec_clear(&bv); set_some_bits(&bv, 32); check_some_bits(&bv, 32); git_bitvec_clear(&bv); set_some_bits(&bv, 64); check_some_bits(&bv, 64); git_bitvec_free(&bv); cl_git_pass(git_bitvec_init(&bv, 128)); set_some_bits(&bv, 32); check_some_bits(&bv, 32); set_some_bits(&bv, 128); check_some_bits(&bv, 128); git_bitvec_free(&bv); cl_git_pass(git_bitvec_init(&bv, 4000)); set_some_bits(&bv, 4000); check_some_bits(&bv, 4000); git_bitvec_free(&bv); }
libgit2-main
tests/util/bitvec.c
#include "clar_libgit2.h" #include "filebuf.h" /* make sure git_filebuf_open doesn't delete an existing lock */ void test_filebuf__0(void) { git_filebuf file = GIT_FILEBUF_INIT; int fd; char test[] = "test", testlock[] = "test.lock"; fd = p_creat(testlock, 0744); /* -V536 */ cl_must_pass(fd); cl_must_pass(p_close(fd)); cl_git_fail(git_filebuf_open(&file, test, 0, 0666)); cl_assert(git_fs_path_exists(testlock)); cl_must_pass(p_unlink(testlock)); } /* make sure GIT_FILEBUF_APPEND works as expected */ void test_filebuf__1(void) { git_filebuf file = GIT_FILEBUF_INIT; char test[] = "test"; cl_git_mkfile(test, "libgit2 rocks\n"); cl_git_pass(git_filebuf_open(&file, test, GIT_FILEBUF_APPEND, 0666)); cl_git_pass(git_filebuf_printf(&file, "%s\n", "libgit2 rocks")); cl_git_pass(git_filebuf_commit(&file)); cl_assert_equal_file("libgit2 rocks\nlibgit2 rocks\n", 0, test); cl_must_pass(p_unlink(test)); } /* make sure git_filebuf_write writes large buffer correctly */ void test_filebuf__2(void) { git_filebuf file = GIT_FILEBUF_INIT; char test[] = "test"; unsigned char buf[4096 * 4]; /* 2 * WRITE_BUFFER_SIZE */ memset(buf, 0xfe, sizeof(buf)); cl_git_pass(git_filebuf_open(&file, test, 0, 0666)); cl_git_pass(git_filebuf_write(&file, buf, sizeof(buf))); cl_git_pass(git_filebuf_commit(&file)); cl_assert_equal_file((char *)buf, sizeof(buf), test); cl_must_pass(p_unlink(test)); } /* make sure git_filebuf_cleanup clears the buffer */ void test_filebuf__4(void) { git_filebuf file = GIT_FILEBUF_INIT; char test[] = "test"; cl_assert(file.buffer == NULL); cl_git_pass(git_filebuf_open(&file, test, 0, 0666)); cl_assert(file.buffer != NULL); git_filebuf_cleanup(&file); cl_assert(file.buffer == NULL); } /* make sure git_filebuf_commit clears the buffer */ void test_filebuf__5(void) { git_filebuf file = GIT_FILEBUF_INIT; char test[] = "test"; cl_assert(file.buffer == NULL); cl_git_pass(git_filebuf_open(&file, test, 0, 0666)); cl_assert(file.buffer != NULL); cl_git_pass(git_filebuf_printf(&file, "%s\n", "libgit2 rocks")); cl_assert(file.buffer != NULL); cl_git_pass(git_filebuf_commit(&file)); cl_assert(file.buffer == NULL); cl_must_pass(p_unlink(test)); } /* make sure git_filebuf_commit takes umask into account */ void test_filebuf__umask(void) { git_filebuf file = GIT_FILEBUF_INIT; char test[] = "test"; struct stat statbuf; mode_t mask, os_mask; #ifdef GIT_WIN32 os_mask = 0600; #else os_mask = 0777; #endif p_umask(mask = p_umask(0)); cl_assert(file.buffer == NULL); cl_git_pass(git_filebuf_open(&file, test, 0, 0666)); cl_assert(file.buffer != NULL); cl_git_pass(git_filebuf_printf(&file, "%s\n", "libgit2 rocks")); cl_assert(file.buffer != NULL); cl_git_pass(git_filebuf_commit(&file)); cl_assert(file.buffer == NULL); cl_must_pass(p_stat("test", &statbuf)); cl_assert_equal_i(statbuf.st_mode & os_mask, (0666 & ~mask) & os_mask); cl_must_pass(p_unlink(test)); } void test_filebuf__rename_error(void) { git_filebuf file = GIT_FILEBUF_INIT; char *dir = "subdir", *test = "subdir/test", *test_lock = "subdir/test.lock"; int fd; #ifndef GIT_WIN32 cl_skip(); #endif cl_git_pass(p_mkdir(dir, 0666)); cl_git_mkfile(test, "dummy content"); fd = p_open(test, O_RDONLY); cl_assert(fd > 0); cl_git_pass(git_filebuf_open(&file, test, 0, 0666)); cl_git_pass(git_filebuf_printf(&file, "%s\n", "libgit2 rocks")); cl_assert_equal_i(true, git_fs_path_exists(test_lock)); cl_git_fail(git_filebuf_commit(&file)); p_close(fd); git_filebuf_cleanup(&file); cl_assert_equal_i(false, git_fs_path_exists(test_lock)); } void test_filebuf__symlink_follow(void) { git_filebuf file = GIT_FILEBUF_INIT; const char *dir = "linkdir", *source = "linkdir/link"; if (!git_fs_path_supports_symlinks(clar_sandbox_path())) cl_skip(); cl_git_pass(p_mkdir(dir, 0777)); cl_git_pass(p_symlink("target", source)); cl_git_pass(git_filebuf_open(&file, source, 0, 0666)); cl_git_pass(git_filebuf_printf(&file, "%s\n", "libgit2 rocks")); cl_assert_equal_i(true, git_fs_path_exists("linkdir/target.lock")); cl_git_pass(git_filebuf_commit(&file)); cl_assert_equal_i(true, git_fs_path_exists("linkdir/target")); git_filebuf_cleanup(&file); /* The second time around, the target file does exist */ cl_git_pass(git_filebuf_open(&file, source, 0, 0666)); cl_git_pass(git_filebuf_printf(&file, "%s\n", "libgit2 rocks")); cl_assert_equal_i(true, git_fs_path_exists("linkdir/target.lock")); cl_git_pass(git_filebuf_commit(&file)); cl_assert_equal_i(true, git_fs_path_exists("linkdir/target")); git_filebuf_cleanup(&file); cl_git_pass(git_futils_rmdir_r(dir, NULL, GIT_RMDIR_REMOVE_FILES)); } void test_filebuf__symlink_follow_absolute_paths(void) { git_filebuf file = GIT_FILEBUF_INIT; git_str source = GIT_STR_INIT, target = GIT_STR_INIT; if (!git_fs_path_supports_symlinks(clar_sandbox_path())) cl_skip(); cl_git_pass(git_str_joinpath(&source, clar_sandbox_path(), "linkdir/link")); cl_git_pass(git_str_joinpath(&target, clar_sandbox_path(), "linkdir/target")); cl_git_pass(p_mkdir("linkdir", 0777)); cl_git_pass(p_symlink(target.ptr, source.ptr)); cl_git_pass(git_filebuf_open(&file, source.ptr, 0, 0666)); cl_git_pass(git_filebuf_printf(&file, "%s\n", "libgit2 rocks")); cl_assert_equal_i(true, git_fs_path_exists("linkdir/target.lock")); cl_git_pass(git_filebuf_commit(&file)); cl_assert_equal_i(true, git_fs_path_exists("linkdir/target")); git_filebuf_cleanup(&file); git_str_dispose(&source); git_str_dispose(&target); cl_git_pass(git_futils_rmdir_r("linkdir", NULL, GIT_RMDIR_REMOVE_FILES)); } void test_filebuf__symlink_depth(void) { git_filebuf file = GIT_FILEBUF_INIT; const char *dir = "linkdir", *source = "linkdir/link"; if (!git_fs_path_supports_symlinks(clar_sandbox_path())) cl_skip(); cl_git_pass(p_mkdir(dir, 0777)); /* Endless loop */ cl_git_pass(p_symlink("link", source)); cl_git_fail(git_filebuf_open(&file, source, 0, 0666)); cl_git_pass(git_futils_rmdir_r(dir, NULL, GIT_RMDIR_REMOVE_FILES)); } void test_filebuf__hidden_file(void) { #ifndef GIT_WIN32 cl_skip(); #else git_filebuf file = GIT_FILEBUF_INIT; char *dir = "hidden", *test = "hidden/test"; bool hidden; cl_git_pass(p_mkdir(dir, 0666)); cl_git_mkfile(test, "dummy content"); cl_git_pass(git_win32__set_hidden(test, true)); cl_git_pass(git_win32__hidden(&hidden, test)); cl_assert(hidden); cl_git_pass(git_filebuf_open(&file, test, 0, 0666)); cl_git_pass(git_filebuf_printf(&file, "%s\n", "libgit2 rocks")); cl_git_pass(git_filebuf_commit(&file)); git_filebuf_cleanup(&file); #endif } void test_filebuf__detects_directory(void) { git_filebuf file = GIT_FILEBUF_INIT; cl_must_pass(p_mkdir("foo", 0777)); cl_git_fail_with(GIT_EDIRECTORY, git_filebuf_open(&file, "foo", 0, 0666)); cl_must_pass(p_rmdir("foo")); }
libgit2-main
tests/util/filebuf.c
#include "clar_libgit2.h" #include "pqueue.h" static int cmp_ints(const void *v1, const void *v2) { int i1 = *(int *)v1, i2 = *(int *)v2; return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0; } void test_pqueue__items_are_put_in_order(void) { git_pqueue pq; int i, vals[20]; cl_git_pass(git_pqueue_init(&pq, 0, 20, cmp_ints)); for (i = 0; i < 20; ++i) { if (i < 10) vals[i] = 10 - i; /* 10 down to 1 */ else vals[i] = i + 1; /* 11 up to 20 */ cl_git_pass(git_pqueue_insert(&pq, &vals[i])); } cl_assert_equal_i(20, git_pqueue_size(&pq)); for (i = 1; i <= 20; ++i) { void *p = git_pqueue_pop(&pq); cl_assert(p); cl_assert_equal_i(i, *(int *)p); } cl_assert_equal_i(0, git_pqueue_size(&pq)); git_pqueue_free(&pq); } void test_pqueue__interleave_inserts_and_pops(void) { git_pqueue pq; int chunk, v, i, vals[200]; cl_git_pass(git_pqueue_init(&pq, 0, 20, cmp_ints)); for (v = 0, chunk = 20; chunk <= 200; chunk += 20) { /* push the next 20 */ for (; v < chunk; ++v) { vals[v] = (v & 1) ? 200 - v : v; cl_git_pass(git_pqueue_insert(&pq, &vals[v])); } /* pop the lowest 10 */ for (i = 0; i < 10; ++i) (void)git_pqueue_pop(&pq); } cl_assert_equal_i(100, git_pqueue_size(&pq)); /* at this point, we've popped 0-99 */ for (v = 100; v < 200; ++v) { void *p = git_pqueue_pop(&pq); cl_assert(p); cl_assert_equal_i(v, *(int *)p); } cl_assert_equal_i(0, git_pqueue_size(&pq)); git_pqueue_free(&pq); } void test_pqueue__max_heap_size(void) { git_pqueue pq; int i, vals[100]; cl_git_pass(git_pqueue_init(&pq, GIT_PQUEUE_FIXED_SIZE, 50, cmp_ints)); for (i = 0; i < 100; ++i) { vals[i] = (i & 1) ? 100 - i : i; cl_git_pass(git_pqueue_insert(&pq, &vals[i])); } cl_assert_equal_i(50, git_pqueue_size(&pq)); for (i = 50; i < 100; ++i) { void *p = git_pqueue_pop(&pq); cl_assert(p); cl_assert_equal_i(i, *(int *)p); } cl_assert_equal_i(0, git_pqueue_size(&pq)); git_pqueue_free(&pq); } void test_pqueue__max_heap_size_without_comparison(void) { git_pqueue pq; int i, vals[100] = { 0 }; cl_git_pass(git_pqueue_init(&pq, GIT_PQUEUE_FIXED_SIZE, 50, NULL)); for (i = 0; i < 100; ++i) cl_git_pass(git_pqueue_insert(&pq, &vals[i])); cl_assert_equal_i(50, git_pqueue_size(&pq)); /* As we have no comparison function, we cannot make any * actual assumptions about which entries are part of the * pqueue */ for (i = 0; i < 50; ++i) cl_assert(git_pqueue_pop(&pq)); cl_assert_equal_i(0, git_pqueue_size(&pq)); git_pqueue_free(&pq); } static int cmp_ints_like_commit_time(const void *a, const void *b) { return *((const int *)a) < *((const int *)b); } void test_pqueue__interleaved_pushes_and_pops(void) { git_pqueue pq; int i, j, *val; static int commands[] = { 6, 9, 8, 0, 5, 0, 7, 0, 4, 3, 0, 0, 0, 4, 0, 2, 0, 1, 0, 0, -1 }; static int expected[] = { 9, 8, 7, 6, 5, 4, 4, 3, 2, 1, -1 }; cl_git_pass(git_pqueue_init(&pq, 0, 10, cmp_ints_like_commit_time)); for (i = 0, j = 0; commands[i] >= 0; ++i) { if (!commands[i]) { cl_assert((val = git_pqueue_pop(&pq)) != NULL); cl_assert_equal_i(expected[j], *val); ++j; } else { cl_git_pass(git_pqueue_insert(&pq, &commands[i])); } } cl_assert_equal_i(0, git_pqueue_size(&pq)); git_pqueue_free(&pq); }
libgit2-main
tests/util/pqueue.c
#include "clar_libgit2.h" #include "hash.h" #define FIXTURE_DIR "sha1" #ifdef GIT_SHA1_WIN32 static git_hash_win32_provider_t orig_provider; #endif void test_sha1__initialize(void) { #ifdef GIT_SHA1_WIN32 orig_provider = git_hash_win32_provider(); #endif cl_fixture_sandbox(FIXTURE_DIR); } void test_sha1__cleanup(void) { #ifdef GIT_SHA1_WIN32 git_hash_win32_set_provider(orig_provider); #endif cl_fixture_cleanup(FIXTURE_DIR); } static int sha1_file(unsigned char *out, const char *filename) { git_hash_ctx ctx; char buf[2048]; int fd, ret; ssize_t read_len; fd = p_open(filename, O_RDONLY); cl_assert(fd >= 0); cl_git_pass(git_hash_ctx_init(&ctx, GIT_HASH_ALGORITHM_SHA1)); while ((read_len = p_read(fd, buf, 2048)) > 0) cl_git_pass(git_hash_update(&ctx, buf, (size_t)read_len)); cl_assert_equal_i(0, read_len); p_close(fd); ret = git_hash_final(out, &ctx); git_hash_ctx_cleanup(&ctx); return ret; } void test_sha1__sum(void) { unsigned char expected[GIT_HASH_SHA1_SIZE] = { 0x4e, 0x72, 0x67, 0x9e, 0x3e, 0xa4, 0xd0, 0x4e, 0x0c, 0x64, 0x2f, 0x02, 0x9e, 0x61, 0xeb, 0x80, 0x56, 0xc7, 0xed, 0x94 }; unsigned char actual[GIT_HASH_SHA1_SIZE]; cl_git_pass(sha1_file(actual, FIXTURE_DIR "/hello_c")); cl_assert_equal_i(0, memcmp(expected, actual, GIT_HASH_SHA1_SIZE)); } /* test that sha1 collision detection works when enabled */ void test_sha1__detect_collision_attack(void) { unsigned char actual[GIT_HASH_SHA1_SIZE]; unsigned char expected[GIT_HASH_SHA1_SIZE] = { 0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a }; #ifdef GIT_SHA1_COLLISIONDETECT GIT_UNUSED(&expected); cl_git_fail(sha1_file(actual, FIXTURE_DIR "/shattered-1.pdf")); cl_assert_equal_s("SHA1 collision attack detected", git_error_last()->message); #else cl_git_pass(sha1_file(actual, FIXTURE_DIR "/shattered-1.pdf")); cl_assert_equal_i(0, memcmp(expected, actual, GIT_HASH_SHA1_SIZE)); #endif } void test_sha1__win32_providers(void) { #ifdef GIT_SHA1_WIN32 unsigned char expected[GIT_HASH_SHA1_SIZE] = { 0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a }; unsigned char actual[GIT_HASH_SHA1_SIZE]; git_hash_win32_set_provider(GIT_HASH_WIN32_CRYPTOAPI); cl_git_pass(sha1_file(actual, FIXTURE_DIR "/shattered-1.pdf")); cl_assert_equal_i(0, memcmp(expected, actual, GIT_HASH_SHA1_SIZE)); git_hash_win32_set_provider(GIT_HASH_WIN32_CNG); cl_git_pass(sha1_file(actual, FIXTURE_DIR "/shattered-1.pdf")); cl_assert_equal_i(0, memcmp(expected, actual, GIT_HASH_SHA1_SIZE)); #endif }
libgit2-main
tests/util/sha1.c
#include "clar_libgit2.h" #include "futils.h" #include "posix.h" void test_copy__file(void) { struct stat st = {0}; const char *content = "This is some stuff to copy\n"; cl_git_mkfile("copy_me", content); cl_git_pass(git_futils_cp("copy_me", "copy_me_two", 0664)); cl_git_pass(git_fs_path_lstat("copy_me_two", &st)); cl_assert(S_ISREG(st.st_mode)); if (!cl_is_env_set("GITTEST_FLAKY_STAT")) cl_assert_equal_sz(strlen(content), (size_t)st.st_size); cl_git_pass(p_unlink("copy_me_two")); cl_git_pass(p_unlink("copy_me")); } void test_copy__file_in_dir(void) { struct stat st = {0}; const char *content = "This is some other stuff to copy\n"; cl_git_pass(git_futils_mkdir("an_dir/in_a_dir", 0775, GIT_MKDIR_PATH)); cl_git_mkfile("an_dir/in_a_dir/copy_me", content); cl_assert(git_fs_path_isdir("an_dir")); cl_git_pass(git_futils_mkpath2file ("an_dir/second_dir/and_more/copy_me_two", 0775)); cl_git_pass(git_futils_cp ("an_dir/in_a_dir/copy_me", "an_dir/second_dir/and_more/copy_me_two", 0664)); cl_git_pass(git_fs_path_lstat("an_dir/second_dir/and_more/copy_me_two", &st)); cl_assert(S_ISREG(st.st_mode)); if (!cl_is_env_set("GITTEST_FLAKY_STAT")) cl_assert_equal_sz(strlen(content), (size_t)st.st_size); cl_git_pass(git_futils_rmdir_r("an_dir", NULL, GIT_RMDIR_REMOVE_FILES)); cl_assert(!git_fs_path_isdir("an_dir")); } #ifndef GIT_WIN32 static void assert_hard_link(const char *path) { /* we assert this by checking that there's more than one link to the file */ struct stat st; cl_assert(git_fs_path_isfile(path)); cl_git_pass(p_stat(path, &st)); cl_assert(st.st_nlink > 1); } #endif void test_copy__tree(void) { struct stat st; const char *content = "File content\n"; cl_git_pass(git_futils_mkdir("src/b", 0775, GIT_MKDIR_PATH)); cl_git_pass(git_futils_mkdir("src/c/d", 0775, GIT_MKDIR_PATH)); cl_git_pass(git_futils_mkdir("src/c/e", 0775, GIT_MKDIR_PATH)); cl_git_mkfile("src/f1", content); cl_git_mkfile("src/b/f2", content); cl_git_mkfile("src/c/f3", content); cl_git_mkfile("src/c/d/f4", content); cl_git_mkfile("src/c/d/.f5", content); #ifndef GIT_WIN32 cl_assert(p_symlink("../../b/f2", "src/c/d/l1") == 0); #endif cl_assert(git_fs_path_isdir("src")); cl_assert(git_fs_path_isdir("src/b")); cl_assert(git_fs_path_isdir("src/c/d")); cl_assert(git_fs_path_isfile("src/c/d/f4")); /* copy with no empty dirs, yes links, no dotfiles, no overwrite */ cl_git_pass( git_futils_cp_r("src", "t1", GIT_CPDIR_COPY_SYMLINKS, 0) ); cl_assert(git_fs_path_isdir("t1")); cl_assert(git_fs_path_isdir("t1/b")); cl_assert(git_fs_path_isdir("t1/c")); cl_assert(git_fs_path_isdir("t1/c/d")); cl_assert(!git_fs_path_isdir("t1/c/e")); cl_assert(git_fs_path_isfile("t1/f1")); cl_assert(git_fs_path_isfile("t1/b/f2")); cl_assert(git_fs_path_isfile("t1/c/f3")); cl_assert(git_fs_path_isfile("t1/c/d/f4")); cl_assert(!git_fs_path_isfile("t1/c/d/.f5")); memset(&st, 0, sizeof(struct stat)); cl_git_pass(git_fs_path_lstat("t1/c/f3", &st)); cl_assert(S_ISREG(st.st_mode)); if (!cl_is_env_set("GITTEST_FLAKY_STAT")) cl_assert_equal_sz(strlen(content), (size_t)st.st_size); #ifndef GIT_WIN32 memset(&st, 0, sizeof(struct stat)); cl_git_pass(git_fs_path_lstat("t1/c/d/l1", &st)); cl_assert(S_ISLNK(st.st_mode)); #endif cl_git_pass(git_futils_rmdir_r("t1", NULL, GIT_RMDIR_REMOVE_FILES)); cl_assert(!git_fs_path_isdir("t1")); /* copy with empty dirs, no links, yes dotfiles, no overwrite */ cl_git_pass( git_futils_cp_r("src", "t2", GIT_CPDIR_CREATE_EMPTY_DIRS | GIT_CPDIR_COPY_DOTFILES, 0) ); cl_assert(git_fs_path_isdir("t2")); cl_assert(git_fs_path_isdir("t2/b")); cl_assert(git_fs_path_isdir("t2/c")); cl_assert(git_fs_path_isdir("t2/c/d")); cl_assert(git_fs_path_isdir("t2/c/e")); cl_assert(git_fs_path_isfile("t2/f1")); cl_assert(git_fs_path_isfile("t2/b/f2")); cl_assert(git_fs_path_isfile("t2/c/f3")); cl_assert(git_fs_path_isfile("t2/c/d/f4")); cl_assert(git_fs_path_isfile("t2/c/d/.f5")); #ifndef GIT_WIN32 memset(&st, 0, sizeof(struct stat)); cl_git_fail(git_fs_path_lstat("t2/c/d/l1", &st)); #endif cl_git_pass(git_futils_rmdir_r("t2", NULL, GIT_RMDIR_REMOVE_FILES)); cl_assert(!git_fs_path_isdir("t2")); #ifndef GIT_WIN32 cl_git_pass(git_futils_cp_r("src", "t3", GIT_CPDIR_CREATE_EMPTY_DIRS | GIT_CPDIR_LINK_FILES, 0)); cl_assert(git_fs_path_isdir("t3")); cl_assert(git_fs_path_isdir("t3")); cl_assert(git_fs_path_isdir("t3/b")); cl_assert(git_fs_path_isdir("t3/c")); cl_assert(git_fs_path_isdir("t3/c/d")); cl_assert(git_fs_path_isdir("t3/c/e")); assert_hard_link("t3/f1"); assert_hard_link("t3/b/f2"); assert_hard_link("t3/c/f3"); assert_hard_link("t3/c/d/f4"); #endif cl_git_pass(git_futils_rmdir_r("src", NULL, GIT_RMDIR_REMOVE_FILES)); }
libgit2-main
tests/util/copy.c
#include "clar_libgit2.h" /* compare prefixes */ void test_string__0(void) { cl_assert(git__prefixcmp("", "") == 0); cl_assert(git__prefixcmp("a", "") == 0); cl_assert(git__prefixcmp("", "a") < 0); cl_assert(git__prefixcmp("a", "b") < 0); cl_assert(git__prefixcmp("b", "a") > 0); cl_assert(git__prefixcmp("ab", "a") == 0); cl_assert(git__prefixcmp("ab", "ac") < 0); cl_assert(git__prefixcmp("ab", "aa") > 0); } /* compare suffixes */ void test_string__1(void) { cl_assert(git__suffixcmp("", "") == 0); cl_assert(git__suffixcmp("a", "") == 0); cl_assert(git__suffixcmp("", "a") < 0); cl_assert(git__suffixcmp("a", "b") < 0); cl_assert(git__suffixcmp("b", "a") > 0); cl_assert(git__suffixcmp("ba", "a") == 0); cl_assert(git__suffixcmp("zaa", "ac") < 0); cl_assert(git__suffixcmp("zaz", "ac") > 0); } /* compare icase sorting with case equality */ void test_string__2(void) { cl_assert(git__strcasesort_cmp("", "") == 0); cl_assert(git__strcasesort_cmp("foo", "foo") == 0); cl_assert(git__strcasesort_cmp("foo", "bar") > 0); cl_assert(git__strcasesort_cmp("bar", "foo") < 0); cl_assert(git__strcasesort_cmp("foo", "FOO") > 0); cl_assert(git__strcasesort_cmp("FOO", "foo") < 0); cl_assert(git__strcasesort_cmp("foo", "BAR") > 0); cl_assert(git__strcasesort_cmp("BAR", "foo") < 0); cl_assert(git__strcasesort_cmp("fooBar", "foobar") < 0); } /* compare prefixes with len */ void test_string__prefixncmp(void) { cl_assert(git__prefixncmp("", 0, "") == 0); cl_assert(git__prefixncmp("a", 1, "") == 0); cl_assert(git__prefixncmp("", 0, "a") < 0); cl_assert(git__prefixncmp("a", 1, "b") < 0); cl_assert(git__prefixncmp("b", 1, "a") > 0); cl_assert(git__prefixncmp("ab", 2, "a") == 0); cl_assert(git__prefixncmp("ab", 1, "a") == 0); cl_assert(git__prefixncmp("ab", 2, "ac") < 0); cl_assert(git__prefixncmp("a", 1, "ac") < 0); cl_assert(git__prefixncmp("ab", 1, "ac") < 0); cl_assert(git__prefixncmp("ab", 2, "aa") > 0); cl_assert(git__prefixncmp("ab", 1, "aa") < 0); } /* compare prefixes with len */ void test_string__prefixncmp_icase(void) { cl_assert(git__prefixncmp_icase("", 0, "") == 0); cl_assert(git__prefixncmp_icase("a", 1, "") == 0); cl_assert(git__prefixncmp_icase("", 0, "a") < 0); cl_assert(git__prefixncmp_icase("a", 1, "b") < 0); cl_assert(git__prefixncmp_icase("A", 1, "b") < 0); cl_assert(git__prefixncmp_icase("a", 1, "B") < 0); cl_assert(git__prefixncmp_icase("b", 1, "a") > 0); cl_assert(git__prefixncmp_icase("B", 1, "a") > 0); cl_assert(git__prefixncmp_icase("b", 1, "A") > 0); cl_assert(git__prefixncmp_icase("ab", 2, "a") == 0); cl_assert(git__prefixncmp_icase("Ab", 2, "a") == 0); cl_assert(git__prefixncmp_icase("ab", 2, "A") == 0); cl_assert(git__prefixncmp_icase("ab", 1, "a") == 0); cl_assert(git__prefixncmp_icase("ab", 2, "ac") < 0); cl_assert(git__prefixncmp_icase("Ab", 2, "ac") < 0); cl_assert(git__prefixncmp_icase("ab", 2, "Ac") < 0); cl_assert(git__prefixncmp_icase("a", 1, "ac") < 0); cl_assert(git__prefixncmp_icase("ab", 1, "ac") < 0); cl_assert(git__prefixncmp_icase("ab", 2, "aa") > 0); cl_assert(git__prefixncmp_icase("ab", 1, "aa") < 0); } void test_string__strcmp(void) { cl_assert(git__strcmp("", "") == 0); cl_assert(git__strcmp("foo", "foo") == 0); cl_assert(git__strcmp("Foo", "foo") < 0); cl_assert(git__strcmp("foo", "FOO") > 0); cl_assert(git__strcmp("foo", "fOO") > 0); cl_assert(strcmp("rt\303\202of", "rt dev\302\266h") > 0); cl_assert(strcmp("e\342\202\254ghi=", "et") > 0); cl_assert(strcmp("rt dev\302\266h", "rt\303\202of") < 0); cl_assert(strcmp("et", "e\342\202\254ghi=") < 0); cl_assert(strcmp("\303\215", "\303\255") < 0); cl_assert(git__strcmp("rt\303\202of", "rt dev\302\266h") > 0); cl_assert(git__strcmp("e\342\202\254ghi=", "et") > 0); cl_assert(git__strcmp("rt dev\302\266h", "rt\303\202of") < 0); cl_assert(git__strcmp("et", "e\342\202\254ghi=") < 0); cl_assert(git__strcmp("\303\215", "\303\255") < 0); } void test_string__strcasecmp(void) { cl_assert(git__strcasecmp("", "") == 0); cl_assert(git__strcasecmp("foo", "foo") == 0); cl_assert(git__strcasecmp("foo", "Foo") == 0); cl_assert(git__strcasecmp("foo", "FOO") == 0); cl_assert(git__strcasecmp("foo", "fOO") == 0); cl_assert(strcasecmp("rt\303\202of", "rt dev\302\266h") > 0); cl_assert(strcasecmp("e\342\202\254ghi=", "et") > 0); cl_assert(strcasecmp("rt dev\302\266h", "rt\303\202of") < 0); cl_assert(strcasecmp("et", "e\342\202\254ghi=") < 0); cl_assert(strcasecmp("\303\215", "\303\255") < 0); cl_assert(git__strcasecmp("rt\303\202of", "rt dev\302\266h") > 0); cl_assert(git__strcasecmp("e\342\202\254ghi=", "et") > 0); cl_assert(git__strcasecmp("rt dev\302\266h", "rt\303\202of") < 0); cl_assert(git__strcasecmp("et", "e\342\202\254ghi=") < 0); cl_assert(git__strcasecmp("\303\215", "\303\255") < 0); } void test_string__strlcmp(void) { const char foo[3] = { 'f', 'o', 'o' }; cl_assert(git__strlcmp("foo", "foo", 3) == 0); cl_assert(git__strlcmp("foo", foo, 3) == 0); cl_assert(git__strlcmp("foo", "foobar", 3) == 0); cl_assert(git__strlcmp("foobar", "foo", 3) > 0); cl_assert(git__strlcmp("foo", "foobar", 6) < 0); }
libgit2-main
tests/util/string.c
#include "clar_libgit2.h" #include "utf8.h" void test_utf8__char_length(void) { cl_assert_equal_i(0, git_utf8_char_length("", 0)); cl_assert_equal_i(1, git_utf8_char_length("$", 1)); cl_assert_equal_i(5, git_utf8_char_length("abcde", 5)); cl_assert_equal_i(1, git_utf8_char_length("\xc2\xa2", 2)); cl_assert_equal_i(2, git_utf8_char_length("\x24\xc2\xa2", 3)); cl_assert_equal_i(1, git_utf8_char_length("\xf0\x90\x8d\x88", 4)); /* uncontinued character counted as single characters */ cl_assert_equal_i(2, git_utf8_char_length("\x24\xc2", 2)); cl_assert_equal_i(3, git_utf8_char_length("\x24\xc2\xc2\xa2", 4)); /* invalid characters are counted as single characters */ cl_assert_equal_i(4, git_utf8_char_length("\x24\xc0\xc0\x34", 4)); cl_assert_equal_i(4, git_utf8_char_length("\x24\xf5\xfd\xc2", 4)); }
libgit2-main
tests/util/utf8.c
#include "clar_libgit2.h" #include <locale.h> #include "regexp.h" #if LC_ALL > 0 static const char *old_locales[LC_ALL]; #endif static git_regexp regex; void test_regexp__initialize(void) { #if LC_ALL > 0 memset(&old_locales, 0, sizeof(old_locales)); #endif } void test_regexp__cleanup(void) { git_regexp_dispose(&regex); } static void try_set_locale(int category) { #if LC_ALL > 0 old_locales[category] = setlocale(category, NULL); #endif if (!setlocale(category, "UTF-8") && !setlocale(category, "c.utf8") && !setlocale(category, "en_US.UTF-8")) cl_skip(); if (MB_CUR_MAX == 1) cl_fail("Expected locale to be switched to multibyte"); } void test_regexp__compile_ignores_global_locale_ctype(void) { try_set_locale(LC_CTYPE); cl_git_pass(git_regexp_compile(&regex, "[\xc0-\xff][\x80-\xbf]", 0)); } void test_regexp__compile_ignores_global_locale_collate(void) { #ifdef GIT_WIN32 cl_skip(); #endif try_set_locale(LC_COLLATE); cl_git_pass(git_regexp_compile(&regex, "[\xc0-\xff][\x80-\xbf]", 0)); } void test_regexp__regex_matches_digits_with_locale(void) { char c, str[2]; #ifdef GIT_WIN32 cl_skip(); #endif try_set_locale(LC_COLLATE); try_set_locale(LC_CTYPE); cl_git_pass(git_regexp_compile(&regex, "[[:digit:]]", 0)); str[1] = '\0'; for (c = '0'; c <= '9'; c++) { str[0] = c; cl_git_pass(git_regexp_match(&regex, str)); } } void test_regexp__regex_matches_alphabet_with_locale(void) { char c, str[2]; #ifdef GIT_WIN32 cl_skip(); #endif try_set_locale(LC_COLLATE); try_set_locale(LC_CTYPE); cl_git_pass(git_regexp_compile(&regex, "[[:alpha:]]", 0)); str[1] = '\0'; for (c = 'a'; c <= 'z'; c++) { str[0] = c; cl_git_pass(git_regexp_match(&regex, str)); } for (c = 'A'; c <= 'Z'; c++) { str[0] = c; cl_git_pass(git_regexp_match(&regex, str)); } } void test_regexp__simple_search_matches(void) { cl_git_pass(git_regexp_compile(&regex, "a", 0)); cl_git_pass(git_regexp_search(&regex, "a", 0, NULL)); } void test_regexp__case_insensitive_search_matches(void) { cl_git_pass(git_regexp_compile(&regex, "a", GIT_REGEXP_ICASE)); cl_git_pass(git_regexp_search(&regex, "A", 0, NULL)); } void test_regexp__nonmatching_search_returns_error(void) { cl_git_pass(git_regexp_compile(&regex, "a", 0)); cl_git_fail(git_regexp_search(&regex, "b", 0, NULL)); } void test_regexp__search_finds_complete_match(void) { git_regmatch matches[1]; cl_git_pass(git_regexp_compile(&regex, "abc", 0)); cl_git_pass(git_regexp_search(&regex, "abc", 1, matches)); cl_assert_equal_i(matches[0].start, 0); cl_assert_equal_i(matches[0].end, 3); } void test_regexp__search_finds_correct_offsets(void) { git_regmatch matches[3]; cl_git_pass(git_regexp_compile(&regex, "(a*)(b*)", 0)); cl_git_pass(git_regexp_search(&regex, "ab", 3, matches)); cl_assert_equal_i(matches[0].start, 0); cl_assert_equal_i(matches[0].end, 2); cl_assert_equal_i(matches[1].start, 0); cl_assert_equal_i(matches[1].end, 1); cl_assert_equal_i(matches[2].start, 1); cl_assert_equal_i(matches[2].end, 2); } void test_regexp__search_finds_empty_group(void) { git_regmatch matches[3]; cl_git_pass(git_regexp_compile(&regex, "(a*)(b*)c", 0)); cl_git_pass(git_regexp_search(&regex, "ac", 3, matches)); cl_assert_equal_i(matches[0].start, 0); cl_assert_equal_i(matches[0].end, 2); cl_assert_equal_i(matches[1].start, 0); cl_assert_equal_i(matches[1].end, 1); cl_assert_equal_i(matches[2].start, 1); cl_assert_equal_i(matches[2].end, 1); } void test_regexp__search_fills_matches_with_first_matching_groups(void) { git_regmatch matches[2]; cl_git_pass(git_regexp_compile(&regex, "(a)(b)(c)", 0)); cl_git_pass(git_regexp_search(&regex, "abc", 2, matches)); cl_assert_equal_i(matches[0].start, 0); cl_assert_equal_i(matches[0].end, 3); cl_assert_equal_i(matches[1].start, 0); cl_assert_equal_i(matches[1].end, 1); } void test_regexp__search_skips_nonmatching_group(void) { git_regmatch matches[4]; cl_git_pass(git_regexp_compile(&regex, "(a)(b)?(c)", 0)); cl_git_pass(git_regexp_search(&regex, "ac", 4, matches)); cl_assert_equal_i(matches[0].start, 0); cl_assert_equal_i(matches[0].end, 2); cl_assert_equal_i(matches[1].start, 0); cl_assert_equal_i(matches[1].end, 1); cl_assert_equal_i(matches[2].start, -1); cl_assert_equal_i(matches[2].end, -1); cl_assert_equal_i(matches[3].start, 1); cl_assert_equal_i(matches[3].end, 2); } void test_regexp__search_initializes_trailing_nonmatching_groups(void) { git_regmatch matches[3]; cl_git_pass(git_regexp_compile(&regex, "(a)bc", 0)); cl_git_pass(git_regexp_search(&regex, "abc", 3, matches)); cl_assert_equal_i(matches[0].start, 0); cl_assert_equal_i(matches[0].end, 3); cl_assert_equal_i(matches[1].start, 0); cl_assert_equal_i(matches[1].end, 1); cl_assert_equal_i(matches[2].start, -1); cl_assert_equal_i(matches[2].end, -1); }
libgit2-main
tests/util/regexp.c
#ifdef GIT_ASSERT_HARD # undef GIT_ASSERT_HARD #endif #define GIT_ASSERT_HARD 0 #include "clar_libgit2.h" static const char *hello_world = "hello, world"; static const char *fail = "FAIL"; static int dummy_fn(const char *myarg) { GIT_ASSERT_ARG(myarg); GIT_ASSERT_ARG(myarg != hello_world); return 0; } static const char *fn_returns_string(const char *myarg) { GIT_ASSERT_ARG_WITH_RETVAL(myarg, fail); GIT_ASSERT_ARG_WITH_RETVAL(myarg != hello_world, fail); return myarg; } static int bad_math(void) { GIT_ASSERT(1 + 1 == 3); return 42; } static const char *bad_returns_string(void) { GIT_ASSERT_WITH_RETVAL(1 + 1 == 3, NULL); return hello_world; } static int has_cleanup(void) { int error = 42; GIT_ASSERT_WITH_CLEANUP(1 + 1 == 3, { error = 99; goto foobar; }); return 0; foobar: return error; } void test_assert__argument(void) { cl_git_fail(dummy_fn(NULL)); cl_assert(git_error_last()); cl_assert_equal_i(GIT_ERROR_INVALID, git_error_last()->klass); cl_assert_equal_s("invalid argument: 'myarg'", git_error_last()->message); cl_git_fail(dummy_fn(hello_world)); cl_assert(git_error_last()); cl_assert_equal_i(GIT_ERROR_INVALID, git_error_last()->klass); cl_assert_equal_s("invalid argument: 'myarg != hello_world'", git_error_last()->message); cl_git_pass(dummy_fn("foo")); } void test_assert__argument_with_non_int_return_type(void) { const char *foo = "foo"; cl_assert_equal_p(fail, fn_returns_string(NULL)); cl_assert_equal_i(GIT_ERROR_INVALID, git_error_last()->klass); cl_assert_equal_s("invalid argument: 'myarg'", git_error_last()->message); cl_assert_equal_p(fail, fn_returns_string(hello_world)); cl_assert_equal_i(GIT_ERROR_INVALID, git_error_last()->klass); cl_assert_equal_s("invalid argument: 'myarg != hello_world'", git_error_last()->message); cl_assert_equal_p(foo, fn_returns_string(foo)); } void test_assert__argument_with_void_return_type(void) { const char *foo = "foo"; git_error_clear(); fn_returns_string(hello_world); cl_assert_equal_i(GIT_ERROR_INVALID, git_error_last()->klass); cl_assert_equal_s("invalid argument: 'myarg != hello_world'", git_error_last()->message); git_error_clear(); cl_assert_equal_p(foo, fn_returns_string(foo)); cl_assert_equal_p(NULL, git_error_last()); } void test_assert__internal(void) { cl_git_fail(bad_math()); cl_assert(git_error_last()); cl_assert_equal_i(GIT_ERROR_INTERNAL, git_error_last()->klass); cl_assert_equal_s("unrecoverable internal error: '1 + 1 == 3'", git_error_last()->message); cl_assert_equal_p(NULL, bad_returns_string()); cl_assert(git_error_last()); cl_assert_equal_i(GIT_ERROR_INTERNAL, git_error_last()->klass); cl_assert_equal_s("unrecoverable internal error: '1 + 1 == 3'", git_error_last()->message); } void test_assert__with_cleanup(void) { cl_git_fail_with(99, has_cleanup()); cl_assert(git_error_last()); cl_assert_equal_i(GIT_ERROR_INTERNAL, git_error_last()->klass); cl_assert_equal_s("unrecoverable internal error: '1 + 1 == 3'", git_error_last()->message); }
libgit2-main
tests/util/assert.c
#include "clar_libgit2.h" #define assert_sorted(a, cmp) \ _assert_sorted(a, ARRAY_SIZE(a), sizeof(*a), cmp) struct big_entries { char c[311]; }; static void _assert_sorted(void *els, size_t n, size_t elsize, git__sort_r_cmp cmp) { int8_t *p = els; git__qsort_r(p, n, elsize, cmp, NULL); while (n-- > 1) { cl_assert(cmp(p, p + elsize, NULL) <= 0); p += elsize; } } static int cmp_big(const void *_a, const void *_b, void *payload) { const struct big_entries *a = (const struct big_entries *)_a, *b = (const struct big_entries *)_b; GIT_UNUSED(payload); return (a->c[0] < b->c[0]) ? -1 : (a->c[0] > b->c[0]) ? +1 : 0; } static int cmp_int(const void *_a, const void *_b, void *payload) { int a = *(const int *)_a, b = *(const int *)_b; GIT_UNUSED(payload); return (a < b) ? -1 : (a > b) ? +1 : 0; } static int cmp_str(const void *_a, const void *_b, void *payload) { GIT_UNUSED(payload); return strcmp((const char *) _a, (const char *) _b); } void test_qsort__array_with_single_entry(void) { int a[] = { 10 }; assert_sorted(a, cmp_int); } void test_qsort__array_with_equal_entries(void) { int a[] = { 4, 4, 4, 4 }; assert_sorted(a, cmp_int); } void test_qsort__sorted_array(void) { int a[] = { 1, 10 }; assert_sorted(a, cmp_int); } void test_qsort__unsorted_array(void) { int a[] = { 123, 9, 412938, 10, 234, 89 }; assert_sorted(a, cmp_int); } void test_qsort__sorting_strings(void) { char *a[] = { "foo", "bar", "baz" }; assert_sorted(a, cmp_str); } void test_qsort__sorting_big_entries(void) { struct big_entries a[5]; memset(&a, 0, sizeof(a)); memset(a[0].c, 'w', sizeof(a[0].c) - 1); memset(a[1].c, 'c', sizeof(a[1].c) - 1); memset(a[2].c, 'w', sizeof(a[2].c) - 1); memset(a[3].c, 'h', sizeof(a[3].c) - 1); memset(a[4].c, 'a', sizeof(a[4].c) - 1); assert_sorted(a, cmp_big); cl_assert_equal_i(strspn(a[0].c, "a"), sizeof(a[0].c) - 1); cl_assert_equal_i(strspn(a[1].c, "c"), sizeof(a[1].c) - 1); cl_assert_equal_i(strspn(a[2].c, "h"), sizeof(a[2].c) - 1); cl_assert_equal_i(strspn(a[3].c, "w"), sizeof(a[3].c) - 1); cl_assert_equal_i(strspn(a[4].c, "w"), sizeof(a[4].c) - 1); }
libgit2-main
tests/util/qsort.c
#include "clar_libgit2.h" void test_integer__multiply_int64_no_overflow(void) { #if !defined(git__multiply_int64_overflow) int64_t result = 0; cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(0x1))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(0x2))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(-0x2))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(0x7ffffffffffffff))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(-0x7ffffffffffffff))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(0x800000000000000))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(-0x800000000000000))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(0x7fffffffffffffff))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(-0x7fffffffffffffff))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x0), INT64_C(-0x8000000000000000))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(0x1))); cl_assert_equal_i(result, INT64_C(0x1)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(-0x1)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(0x2))); cl_assert_equal_i(result, INT64_C(0x2)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(-0x2))); cl_assert_equal_i(result, INT64_C(-0x2)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(0x7ffffffffffffff))); cl_assert_equal_i(result, INT64_C(0x7ffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(-0x7ffffffffffffff))); cl_assert_equal_i(result, INT64_C(-0x7ffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(0x800000000000000))); cl_assert_equal_i(result, INT64_C(0x800000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(-0x800000000000000))); cl_assert_equal_i(result, INT64_C(-0x800000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(0x7fffffffffffffff))); cl_assert_equal_i(result, INT64_C(0x7fffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(-0x7fffffffffffffff))); cl_assert_equal_i(result, INT64_C(-0x7fffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(0x1))); cl_assert_equal_i(result, INT64_C(-0x1)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(0x1)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(0x2))); cl_assert_equal_i(result, INT64_C(-0x2)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(-0x2))); cl_assert_equal_i(result, INT64_C(0x2)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(0x7ffffffffffffff))); cl_assert_equal_i(result, INT64_C(-0x7ffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(-0x7ffffffffffffff))); cl_assert_equal_i(result, INT64_C(0x7ffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(0x800000000000000))); cl_assert_equal_i(result, INT64_C(-0x800000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(-0x800000000000000))); cl_assert_equal_i(result, INT64_C(0x800000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(0x7fffffffffffffff))); cl_assert_equal_i(result, INT64_C(-0x7fffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(-0x7fffffffffffffff))); cl_assert_equal_i(result, INT64_C(0x7fffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(0x1))); cl_assert_equal_i(result, INT64_C(0x2)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(-0x2)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(0x2))); cl_assert_equal_i(result, INT64_C(0x4)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(-0x2))); cl_assert_equal_i(result, INT64_C(-0x4)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(0x7ffffffffffffff))); cl_assert_equal_i(result, INT64_C(0xffffffffffffffe)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(-0x7ffffffffffffff))); cl_assert_equal_i(result, INT64_C(-0xffffffffffffffe)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(0x800000000000000))); cl_assert_equal_i(result, INT64_C(0x1000000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(-0x800000000000000))); cl_assert_equal_i(result, INT64_C(-0x1000000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(0x1))); cl_assert_equal_i(result, INT64_C(-0x2)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(0x2)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(0x2))); cl_assert_equal_i(result, INT64_C(-0x4)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(-0x2))); cl_assert_equal_i(result, INT64_C(0x4)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(0x7ffffffffffffff))); cl_assert_equal_i(result, INT64_C(-0xffffffffffffffe)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(-0x7ffffffffffffff))); cl_assert_equal_i(result, INT64_C(0xffffffffffffffe)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(0x800000000000000))); cl_assert_equal_i(result, INT64_C(-0x1000000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(-0x800000000000000))); cl_assert_equal_i(result, INT64_C(0x1000000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(-0x4000000000000000))); cl_assert_equal_i(result, INT64_C(-0x8000000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(0x1))); cl_assert_equal_i(result, INT64_C(0x7ffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(-0x7ffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(0x2))); cl_assert_equal_i(result, INT64_C(0xffffffffffffffe)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(-0x2))); cl_assert_equal_i(result, INT64_C(-0xffffffffffffffe)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(0x1))); cl_assert_equal_i(result, INT64_C(-0x7ffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(0x7ffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(0x2))); cl_assert_equal_i(result, INT64_C(-0xffffffffffffffe)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(-0x2))); cl_assert_equal_i(result, INT64_C(0xffffffffffffffe)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(0x1))); cl_assert_equal_i(result, INT64_C(0x800000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(-0x800000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(0x2))); cl_assert_equal_i(result, INT64_C(0x1000000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(-0x2))); cl_assert_equal_i(result, INT64_C(-0x1000000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(0x1))); cl_assert_equal_i(result, INT64_C(-0x800000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(0x800000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(0x2))); cl_assert_equal_i(result, INT64_C(-0x1000000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(-0x2))); cl_assert_equal_i(result, INT64_C(0x1000000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(0x1))); cl_assert_equal_i(result, INT64_C(0x7fffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(-0x7fffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x4000000000000000), INT64_C(0x2))); cl_assert_equal_i(result, INT64_C(-0x8000000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(0x1))); cl_assert_equal_i(result, INT64_C(-0x7fffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(0x7fffffffffffffff)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(0x0))); cl_assert_equal_i(result, INT64_C(0x0)); #endif } void test_integer__multiply_int64_overflow(void) { #if !defined(git__multiply_int64_overflow) int64_t result = 0; cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(0x4000000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(-0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x2), INT64_C(-0x8000000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(-0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x2), INT64_C(-0x8000000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(-0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(-0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(-0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7ffffffffffffff), INT64_C(-0x8000000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(-0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(-0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(-0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7ffffffffffffff), INT64_C(-0x8000000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(-0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(-0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(-0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x800000000000000), INT64_C(-0x8000000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(-0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(-0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(-0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x800000000000000), INT64_C(-0x8000000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x4000000000000000), INT64_C(0x2))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(0x2))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(-0x2))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(-0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(-0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(-0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x7fffffffffffffff), INT64_C(-0x8000000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(0x2))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(-0x2))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(-0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(-0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(-0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x7fffffffffffffff), INT64_C(-0x8000000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(0x2))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(-0x2))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(-0x7ffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(-0x800000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(-0x7fffffffffffffff))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(-0x8000000000000000))); #endif } void test_integer__multiply_int64_edge_cases(void) { #if !defined(git__multiply_int64_overflow) int64_t result = 0; cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(-0x1))); cl_assert_equal_i(result, INT64_C(-0x8000000000000000)); cl_assert(!git__multiply_int64_overflow(&result, INT64_C(-0x1), INT64_C(-0x8000000000000000))); cl_assert_equal_i(result, INT64_C(-0x8000000000000000)); cl_assert(git__multiply_int64_overflow(&result, INT64_C(0x1), INT64_C(-0x8000000000000000))); cl_assert(git__multiply_int64_overflow(&result, INT64_C(-0x8000000000000000), INT64_C(0x1))); #endif }
libgit2-main
tests/util/integer.c
#include "clar_libgit2.h" #include "futils.h" #include "posix.h" static void cleanup_basic_dirs(void *ref) { GIT_UNUSED(ref); git_futils_rmdir_r("d0", NULL, GIT_RMDIR_EMPTY_HIERARCHY); git_futils_rmdir_r("d1", NULL, GIT_RMDIR_EMPTY_HIERARCHY); git_futils_rmdir_r("d2", NULL, GIT_RMDIR_EMPTY_HIERARCHY); git_futils_rmdir_r("d3", NULL, GIT_RMDIR_EMPTY_HIERARCHY); git_futils_rmdir_r("d4", NULL, GIT_RMDIR_EMPTY_HIERARCHY); } void test_mkdir__absolute(void) { git_str path = GIT_STR_INIT; cl_set_cleanup(cleanup_basic_dirs, NULL); git_str_joinpath(&path, clar_sandbox_path(), "d0"); /* make a directory */ cl_assert(!git_fs_path_isdir(path.ptr)); cl_git_pass(git_futils_mkdir(path.ptr, 0755, 0)); cl_assert(git_fs_path_isdir(path.ptr)); git_str_joinpath(&path, path.ptr, "subdir"); cl_assert(!git_fs_path_isdir(path.ptr)); cl_git_pass(git_futils_mkdir(path.ptr, 0755, 0)); cl_assert(git_fs_path_isdir(path.ptr)); /* ensure mkdir_r works for a single subdir */ git_str_joinpath(&path, path.ptr, "another"); cl_assert(!git_fs_path_isdir(path.ptr)); cl_git_pass(git_futils_mkdir_r(path.ptr, 0755)); cl_assert(git_fs_path_isdir(path.ptr)); /* ensure mkdir_r works */ git_str_joinpath(&path, clar_sandbox_path(), "d1/foo/bar/asdf"); cl_assert(!git_fs_path_isdir(path.ptr)); cl_git_pass(git_futils_mkdir_r(path.ptr, 0755)); cl_assert(git_fs_path_isdir(path.ptr)); /* ensure we don't imply recursive */ git_str_joinpath(&path, clar_sandbox_path(), "d2/foo/bar/asdf"); cl_assert(!git_fs_path_isdir(path.ptr)); cl_git_fail(git_futils_mkdir(path.ptr, 0755, 0)); cl_assert(!git_fs_path_isdir(path.ptr)); git_str_dispose(&path); } void test_mkdir__basic(void) { cl_set_cleanup(cleanup_basic_dirs, NULL); /* make a directory */ cl_assert(!git_fs_path_isdir("d0")); cl_git_pass(git_futils_mkdir("d0", 0755, 0)); cl_assert(git_fs_path_isdir("d0")); /* make a path */ cl_assert(!git_fs_path_isdir("d1")); cl_git_pass(git_futils_mkdir("d1/d1.1/d1.2", 0755, GIT_MKDIR_PATH)); cl_assert(git_fs_path_isdir("d1")); cl_assert(git_fs_path_isdir("d1/d1.1")); cl_assert(git_fs_path_isdir("d1/d1.1/d1.2")); /* make a dir exclusively */ cl_assert(!git_fs_path_isdir("d2")); cl_git_pass(git_futils_mkdir("d2", 0755, GIT_MKDIR_EXCL)); cl_assert(git_fs_path_isdir("d2")); /* make exclusive failure */ cl_git_fail(git_futils_mkdir("d2", 0755, GIT_MKDIR_EXCL)); /* make a path exclusively */ cl_assert(!git_fs_path_isdir("d3")); cl_git_pass(git_futils_mkdir("d3/d3.1/d3.2", 0755, GIT_MKDIR_PATH | GIT_MKDIR_EXCL)); cl_assert(git_fs_path_isdir("d3")); cl_assert(git_fs_path_isdir("d3/d3.1/d3.2")); /* make exclusive path failure */ cl_git_fail(git_futils_mkdir("d3/d3.1/d3.2", 0755, GIT_MKDIR_PATH | GIT_MKDIR_EXCL)); /* ??? Should EXCL only apply to the last item in the path? */ /* path with trailing slash? */ cl_assert(!git_fs_path_isdir("d4")); cl_git_pass(git_futils_mkdir("d4/d4.1/", 0755, GIT_MKDIR_PATH)); cl_assert(git_fs_path_isdir("d4/d4.1")); } static void cleanup_basedir(void *ref) { GIT_UNUSED(ref); git_futils_rmdir_r("base", NULL, GIT_RMDIR_EMPTY_HIERARCHY); } void test_mkdir__with_base(void) { #define BASEDIR "base/dir/here" cl_set_cleanup(cleanup_basedir, NULL); cl_git_pass(git_futils_mkdir(BASEDIR, 0755, GIT_MKDIR_PATH)); cl_git_pass(git_futils_mkdir_relative("a", BASEDIR, 0755, 0, NULL)); cl_assert(git_fs_path_isdir(BASEDIR "/a")); cl_git_pass(git_futils_mkdir_relative("b/b1/b2", BASEDIR, 0755, GIT_MKDIR_PATH, NULL)); cl_assert(git_fs_path_isdir(BASEDIR "/b/b1/b2")); /* exclusive with existing base */ cl_git_pass(git_futils_mkdir_relative("c/c1/c2", BASEDIR, 0755, GIT_MKDIR_PATH | GIT_MKDIR_EXCL, NULL)); /* fail: exclusive with duplicated suffix */ cl_git_fail(git_futils_mkdir_relative("c/c1/c3", BASEDIR, 0755, GIT_MKDIR_PATH | GIT_MKDIR_EXCL, NULL)); /* fail: exclusive with any duplicated component */ cl_git_fail(git_futils_mkdir_relative("c/cz/cz", BASEDIR, 0755, GIT_MKDIR_PATH | GIT_MKDIR_EXCL, NULL)); /* success: exclusive without path */ cl_git_pass(git_futils_mkdir_relative("c/c1/c3", BASEDIR, 0755, GIT_MKDIR_EXCL, NULL)); /* path with shorter base and existing dirs */ cl_git_pass(git_futils_mkdir_relative("dir/here/d/", "base", 0755, GIT_MKDIR_PATH, NULL)); cl_assert(git_fs_path_isdir("base/dir/here/d")); /* fail: path with shorter base and existing dirs */ cl_git_fail(git_futils_mkdir_relative("dir/here/e/", "base", 0755, GIT_MKDIR_PATH | GIT_MKDIR_EXCL, NULL)); /* fail: base with missing components */ cl_git_fail(git_futils_mkdir_relative("f/", "base/missing", 0755, GIT_MKDIR_PATH, NULL)); /* success: shift missing component to path */ cl_git_pass(git_futils_mkdir_relative("missing/f/", "base/", 0755, GIT_MKDIR_PATH, NULL)); } static void cleanup_chmod_root(void *ref) { mode_t *mode = ref; if (mode != NULL) { (void)p_umask(*mode); git__free(mode); } git_futils_rmdir_r("r", NULL, GIT_RMDIR_EMPTY_HIERARCHY); } #define check_mode(X,A) check_mode_at_line((X), (A), __FILE__, __func__, __LINE__) static void check_mode_at_line( mode_t expected, mode_t actual, const char *file, const char *func, int line) { /* FAT filesystems don't support exec bit, nor group/world bits */ if (!cl_is_chmod_supported()) { expected &= 0600; actual &= 0600; } clar__assert_equal( file, func, line, "expected_mode != actual_mode", 1, "%07o", (int)expected, (int)(actual & 0777)); } void test_mkdir__chmods(void) { struct stat st; mode_t *old = git__malloc(sizeof(mode_t)); *old = p_umask(022); cl_set_cleanup(cleanup_chmod_root, old); cl_git_pass(git_futils_mkdir("r", 0777, 0)); cl_git_pass(git_futils_mkdir_relative("mode/is/important", "r", 0777, GIT_MKDIR_PATH, NULL)); cl_git_pass(git_fs_path_lstat("r/mode", &st)); check_mode(0755, st.st_mode); cl_git_pass(git_fs_path_lstat("r/mode/is", &st)); check_mode(0755, st.st_mode); cl_git_pass(git_fs_path_lstat("r/mode/is/important", &st)); check_mode(0755, st.st_mode); cl_git_pass(git_futils_mkdir_relative("mode2/is2/important2", "r", 0777, GIT_MKDIR_PATH | GIT_MKDIR_CHMOD, NULL)); cl_git_pass(git_fs_path_lstat("r/mode2", &st)); check_mode(0755, st.st_mode); cl_git_pass(git_fs_path_lstat("r/mode2/is2", &st)); check_mode(0755, st.st_mode); cl_git_pass(git_fs_path_lstat("r/mode2/is2/important2", &st)); check_mode(0777, st.st_mode); cl_git_pass(git_futils_mkdir_relative("mode3/is3/important3", "r", 0777, GIT_MKDIR_PATH | GIT_MKDIR_CHMOD_PATH, NULL)); cl_git_pass(git_fs_path_lstat("r/mode3", &st)); check_mode(0777, st.st_mode); cl_git_pass(git_fs_path_lstat("r/mode3/is3", &st)); check_mode(0777, st.st_mode); cl_git_pass(git_fs_path_lstat("r/mode3/is3/important3", &st)); check_mode(0777, st.st_mode); /* test that we chmod existing dir */ cl_git_pass(git_futils_mkdir_relative("mode/is/important", "r", 0777, GIT_MKDIR_PATH | GIT_MKDIR_CHMOD, NULL)); cl_git_pass(git_fs_path_lstat("r/mode", &st)); check_mode(0755, st.st_mode); cl_git_pass(git_fs_path_lstat("r/mode/is", &st)); check_mode(0755, st.st_mode); cl_git_pass(git_fs_path_lstat("r/mode/is/important", &st)); check_mode(0777, st.st_mode); /* test that we chmod even existing dirs if CHMOD_PATH is set */ cl_git_pass(git_futils_mkdir_relative("mode2/is2/important2.1", "r", 0777, GIT_MKDIR_PATH | GIT_MKDIR_CHMOD_PATH, NULL)); cl_git_pass(git_fs_path_lstat("r/mode2", &st)); check_mode(0777, st.st_mode); cl_git_pass(git_fs_path_lstat("r/mode2/is2", &st)); check_mode(0777, st.st_mode); cl_git_pass(git_fs_path_lstat("r/mode2/is2/important2.1", &st)); check_mode(0777, st.st_mode); } void test_mkdir__keeps_parent_symlinks(void) { #ifndef GIT_WIN32 git_str path = GIT_STR_INIT; cl_set_cleanup(cleanup_basic_dirs, NULL); /* make a directory */ cl_assert(!git_fs_path_isdir("d0")); cl_git_pass(git_futils_mkdir("d0", 0755, 0)); cl_assert(git_fs_path_isdir("d0")); cl_must_pass(symlink("d0", "d1")); cl_assert(git_fs_path_islink("d1")); cl_git_pass(git_futils_mkdir("d1/foo/bar", 0755, GIT_MKDIR_PATH|GIT_MKDIR_REMOVE_SYMLINKS)); cl_assert(git_fs_path_islink("d1")); cl_assert(git_fs_path_isdir("d1/foo/bar")); cl_assert(git_fs_path_isdir("d0/foo/bar")); cl_must_pass(symlink("d0", "d2")); cl_assert(git_fs_path_islink("d2")); git_str_joinpath(&path, clar_sandbox_path(), "d2/other/dir"); cl_git_pass(git_futils_mkdir(path.ptr, 0755, GIT_MKDIR_PATH|GIT_MKDIR_REMOVE_SYMLINKS)); cl_assert(git_fs_path_islink("d2")); cl_assert(git_fs_path_isdir("d2/other/dir")); cl_assert(git_fs_path_isdir("d0/other/dir")); git_str_dispose(&path); #endif } void test_mkdir__mkdir_path_inside_unwriteable_parent(void) { struct stat st; mode_t *old; /* FAT filesystems don't support exec bit, nor group/world bits */ if (!cl_is_chmod_supported()) return; cl_assert((old = git__malloc(sizeof(mode_t))) != NULL); *old = p_umask(022); cl_set_cleanup(cleanup_chmod_root, old); cl_git_pass(git_futils_mkdir("r", 0777, 0)); cl_git_pass(git_futils_mkdir_relative("mode/is/important", "r", 0777, GIT_MKDIR_PATH, NULL)); cl_git_pass(git_fs_path_lstat("r/mode", &st)); check_mode(0755, st.st_mode); cl_must_pass(p_chmod("r/mode", 0111)); cl_git_pass(git_fs_path_lstat("r/mode", &st)); check_mode(0111, st.st_mode); cl_git_pass( git_futils_mkdir_relative("mode/is/okay/inside", "r", 0777, GIT_MKDIR_PATH, NULL)); cl_git_pass(git_fs_path_lstat("r/mode/is/okay/inside", &st)); check_mode(0755, st.st_mode); cl_must_pass(p_chmod("r/mode", 0777)); }
libgit2-main
tests/util/mkdir.c
#include "clar_libgit2.h" #include "futils.h" /* Fixture setup and teardown */ void test_futils__initialize(void) { cl_must_pass(p_mkdir("futils", 0777)); } void test_futils__cleanup(void) { cl_fixture_cleanup("futils"); } void test_futils__writebuffer(void) { git_str out = GIT_STR_INIT, append = GIT_STR_INIT; /* create a new file */ git_str_puts(&out, "hello!\n"); git_str_printf(&out, "this is a %s\n", "test"); cl_git_pass(git_futils_writebuffer(&out, "futils/test-file", O_RDWR|O_CREAT, 0666)); cl_assert_equal_file(out.ptr, out.size, "futils/test-file"); /* append some more data */ git_str_puts(&append, "And some more!\n"); git_str_put(&out, append.ptr, append.size); cl_git_pass(git_futils_writebuffer(&append, "futils/test-file", O_RDWR|O_APPEND, 0666)); cl_assert_equal_file(out.ptr, out.size, "futils/test-file"); git_str_dispose(&out); git_str_dispose(&append); } void test_futils__write_hidden_file(void) { #ifndef GIT_WIN32 cl_skip(); #else git_str out = GIT_STR_INIT, append = GIT_STR_INIT; bool hidden; git_str_puts(&out, "hidden file.\n"); git_futils_writebuffer(&out, "futils/test-file", O_RDWR | O_CREAT, 0666); cl_git_pass(git_win32__set_hidden("futils/test-file", true)); /* append some more data */ git_str_puts(&append, "And some more!\n"); git_str_put(&out, append.ptr, append.size); cl_git_pass(git_futils_writebuffer(&append, "futils/test-file", O_RDWR | O_APPEND, 0666)); cl_assert_equal_file(out.ptr, out.size, "futils/test-file"); cl_git_pass(git_win32__hidden(&hidden, "futils/test-file")); cl_assert(hidden); git_str_dispose(&out); git_str_dispose(&append); #endif } void test_futils__recursive_rmdir_keeps_symlink_targets(void) { if (!git_fs_path_supports_symlinks(clar_sandbox_path())) cl_skip(); cl_git_pass(git_futils_mkdir_r("a/b", 0777)); cl_git_pass(git_futils_mkdir_r("dir-target", 0777)); cl_git_mkfile("dir-target/file", "Contents"); cl_git_mkfile("file-target", "Contents"); cl_must_pass(p_symlink("dir-target", "a/symlink")); cl_must_pass(p_symlink("file-target", "a/b/symlink")); cl_git_pass(git_futils_rmdir_r("a", NULL, GIT_RMDIR_REMOVE_FILES)); cl_assert(git_fs_path_exists("dir-target")); cl_assert(git_fs_path_exists("file-target")); cl_must_pass(p_unlink("dir-target/file")); cl_must_pass(p_rmdir("dir-target")); cl_must_pass(p_unlink("file-target")); } void test_futils__mktmp_umask(void) { #ifdef GIT_WIN32 cl_skip(); #else git_str path = GIT_STR_INIT; struct stat st; int fd; umask(0); cl_assert((fd = git_futils_mktmp(&path, "foo", 0777)) >= 0); cl_must_pass(p_fstat(fd, &st)); cl_assert_equal_i(st.st_mode & 0777, 0777); cl_must_pass(p_unlink(path.ptr)); close(fd); umask(077); cl_assert((fd = git_futils_mktmp(&path, "foo", 0777)) >= 0); cl_must_pass(p_fstat(fd, &st)); cl_assert_equal_i(st.st_mode & 0777, 0700); cl_must_pass(p_unlink(path.ptr)); close(fd); git_str_dispose(&path); #endif }
libgit2-main
tests/util/futils.c
#include "clar_libgit2.h" #include "zstream.h" static const char *data = "This is a test test test of This is a test"; #define INFLATE_EXTRA 2 static void assert_zlib_equal_( const void *expected, size_t e_len, const void *compressed, size_t c_len, const char *msg, const char *file, const char *func, int line) { z_stream stream; char *expanded = git__calloc(1, e_len + INFLATE_EXTRA); cl_assert(expanded); memset(&stream, 0, sizeof(stream)); stream.next_out = (Bytef *)expanded; stream.avail_out = (uInt)(e_len + INFLATE_EXTRA); stream.next_in = (Bytef *)compressed; stream.avail_in = (uInt)c_len; cl_assert(inflateInit(&stream) == Z_OK); cl_assert(inflate(&stream, Z_FINISH)); inflateEnd(&stream); clar__assert_equal( file, func, line, msg, 1, "%d", (int)stream.total_out, (int)e_len); clar__assert_equal( file, func, line, "Buffer len was not exact match", 1, "%d", (int)stream.avail_out, (int)INFLATE_EXTRA); clar__assert( memcmp(expanded, expected, e_len) == 0, file, func, line, "uncompressed data did not match", NULL, 1); git__free(expanded); } #define assert_zlib_equal(E,EL,C,CL) \ assert_zlib_equal_(E, EL, C, CL, #EL " != " #CL, __FILE__, __func__, (int)__LINE__) void test_zstream__basic(void) { git_zstream z = GIT_ZSTREAM_INIT; char out[128]; size_t outlen = sizeof(out); cl_git_pass(git_zstream_init(&z, GIT_ZSTREAM_DEFLATE)); cl_git_pass(git_zstream_set_input(&z, data, strlen(data) + 1)); cl_git_pass(git_zstream_get_output(out, &outlen, &z)); cl_assert(git_zstream_done(&z)); cl_assert(outlen > 0); git_zstream_free(&z); assert_zlib_equal(data, strlen(data) + 1, out, outlen); } void test_zstream__fails_on_trailing_garbage(void) { git_str deflated = GIT_STR_INIT, inflated = GIT_STR_INIT; char i = 0; /* compress a simple string */ git_zstream_deflatebuf(&deflated, "foobar!!", 8); /* append some garbage */ for (i = 0; i < 10; i++) { git_str_putc(&deflated, i); } cl_git_fail(git_zstream_inflatebuf(&inflated, deflated.ptr, deflated.size)); git_str_dispose(&deflated); git_str_dispose(&inflated); } void test_zstream__buffer(void) { git_str out = GIT_STR_INIT; cl_git_pass(git_zstream_deflatebuf(&out, data, strlen(data) + 1)); assert_zlib_equal(data, strlen(data) + 1, out.ptr, out.size); git_str_dispose(&out); } #define BIG_STRING_PART "Big Data IS Big - Long Data IS Long - We need a buffer larger than 1024 x 1024 to make sure we trigger chunked compression - Big Big Data IS Bigger than Big - Long Long Data IS Longer than Long" static void compress_and_decompress_input_various_ways(git_str *input) { git_str out1 = GIT_STR_INIT, out2 = GIT_STR_INIT; git_str inflated = GIT_STR_INIT; size_t i, fixed_size = max(input->size / 2, 256); char *fixed = git__malloc(fixed_size); cl_assert(fixed); /* compress with deflatebuf */ cl_git_pass(git_zstream_deflatebuf(&out1, input->ptr, input->size)); assert_zlib_equal(input->ptr, input->size, out1.ptr, out1.size); /* compress with various fixed size buffer (accumulating the output) */ for (i = 0; i < 3; ++i) { git_zstream zs = GIT_ZSTREAM_INIT; size_t use_fixed_size; switch (i) { case 0: use_fixed_size = 256; break; case 1: use_fixed_size = fixed_size / 2; break; case 2: use_fixed_size = fixed_size; break; } cl_assert(use_fixed_size <= fixed_size); cl_git_pass(git_zstream_init(&zs, GIT_ZSTREAM_DEFLATE)); cl_git_pass(git_zstream_set_input(&zs, input->ptr, input->size)); while (!git_zstream_done(&zs)) { size_t written = use_fixed_size; cl_git_pass(git_zstream_get_output(fixed, &written, &zs)); cl_git_pass(git_str_put(&out2, fixed, written)); } git_zstream_free(&zs); assert_zlib_equal(input->ptr, input->size, out2.ptr, out2.size); /* did both approaches give the same data? */ cl_assert_equal_sz(out1.size, out2.size); cl_assert(!memcmp(out1.ptr, out2.ptr, out1.size)); git_str_dispose(&out2); } cl_git_pass(git_zstream_inflatebuf(&inflated, out1.ptr, out1.size)); cl_assert_equal_i(input->size, inflated.size); cl_assert(memcmp(input->ptr, inflated.ptr, inflated.size) == 0); git_str_dispose(&out1); git_str_dispose(&inflated); git__free(fixed); } void test_zstream__big_data(void) { git_str in = GIT_STR_INIT; size_t scan, target; for (target = 1024; target <= 1024 * 1024 * 4; target *= 8) { /* make a big string that's easy to compress */ git_str_clear(&in); while (in.size < target) cl_git_pass( git_str_put(&in, BIG_STRING_PART, strlen(BIG_STRING_PART))); compress_and_decompress_input_various_ways(&in); /* make a big string that's hard to compress */ srand(0xabad1dea); for (scan = 0; scan < in.size; ++scan) in.ptr[scan] = (char)rand(); compress_and_decompress_input_various_ways(&in); } git_str_dispose(&in); }
libgit2-main
tests/util/zstream.c
#include "clar_libgit2.h" #include "futils.h" #include "fs_path.h" static char *path_save; void test_path__initialize(void) { path_save = cl_getenv("PATH"); } void test_path__cleanup(void) { cl_setenv("PATH", path_save); git__free(path_save); path_save = NULL; } static void check_dirname(const char *A, const char *B) { git_str dir = GIT_STR_INIT; char *dir2; cl_assert(git_fs_path_dirname_r(&dir, A) >= 0); cl_assert_equal_s(B, dir.ptr); git_str_dispose(&dir); cl_assert((dir2 = git_fs_path_dirname(A)) != NULL); cl_assert_equal_s(B, dir2); git__free(dir2); } static void check_basename(const char *A, const char *B) { git_str base = GIT_STR_INIT; char *base2; cl_assert(git_fs_path_basename_r(&base, A) >= 0); cl_assert_equal_s(B, base.ptr); git_str_dispose(&base); cl_assert((base2 = git_fs_path_basename(A)) != NULL); cl_assert_equal_s(B, base2); git__free(base2); } static void check_joinpath(const char *path_a, const char *path_b, const char *expected_path) { git_str joined_path = GIT_STR_INIT; cl_git_pass(git_str_joinpath(&joined_path, path_a, path_b)); cl_assert_equal_s(expected_path, joined_path.ptr); git_str_dispose(&joined_path); } static void check_joinpath_n( const char *path_a, const char *path_b, const char *path_c, const char *path_d, const char *expected_path) { git_str joined_path = GIT_STR_INIT; cl_git_pass(git_str_join_n(&joined_path, '/', 4, path_a, path_b, path_c, path_d)); cl_assert_equal_s(expected_path, joined_path.ptr); git_str_dispose(&joined_path); } static void check_setenv(const char* name, const char* value) { char* check; cl_git_pass(cl_setenv(name, value)); check = cl_getenv(name); if (value) cl_assert_equal_s(value, check); else cl_assert(check == NULL); git__free(check); } /* get the dirname of a path */ void test_path__00_dirname(void) { check_dirname(NULL, "."); check_dirname("", "."); check_dirname("a", "."); check_dirname("/", "/"); check_dirname("/usr", "/"); check_dirname("/usr/", "/"); check_dirname("/usr/lib", "/usr"); check_dirname("/usr/lib/", "/usr"); check_dirname("/usr/lib//", "/usr"); check_dirname("usr/lib", "usr"); check_dirname("usr/lib/", "usr"); check_dirname("usr/lib//", "usr"); check_dirname(".git/", "."); check_dirname(REP16("/abc"), REP15("/abc")); #ifdef GIT_WIN32 check_dirname("C:/", "C:/"); check_dirname("C:", "C:/"); check_dirname("C:/path/", "C:/"); check_dirname("C:/path", "C:/"); check_dirname("//computername/", "//computername/"); check_dirname("//computername", "//computername/"); check_dirname("//computername/path/", "//computername/"); check_dirname("//computername/path", "//computername/"); check_dirname("//computername/sub/path/", "//computername/sub"); check_dirname("//computername/sub/path", "//computername/sub"); #endif } /* get the base name of a path */ void test_path__01_basename(void) { check_basename(NULL, "."); check_basename("", "."); check_basename("a", "a"); check_basename("/", "/"); check_basename("/usr", "usr"); check_basename("/usr/", "usr"); check_basename("/usr/lib", "lib"); check_basename("/usr/lib//", "lib"); check_basename("usr/lib", "lib"); check_basename(REP16("/abc"), "abc"); check_basename(REP1024("/abc"), "abc"); } /* properly join path components */ void test_path__05_joins(void) { check_joinpath("", "", ""); check_joinpath("", "a", "a"); check_joinpath("", "/a", "/a"); check_joinpath("a", "", "a/"); check_joinpath("a", "/", "a/"); check_joinpath("a", "b", "a/b"); check_joinpath("/", "a", "/a"); check_joinpath("/", "", "/"); check_joinpath("/a", "/b", "/a/b"); check_joinpath("/a", "/b/", "/a/b/"); check_joinpath("/a/", "b/", "/a/b/"); check_joinpath("/a/", "/b/", "/a/b/"); check_joinpath("/abcd", "/defg", "/abcd/defg"); check_joinpath("/abcd", "/defg/", "/abcd/defg/"); check_joinpath("/abcd/", "defg/", "/abcd/defg/"); check_joinpath("/abcd/", "/defg/", "/abcd/defg/"); check_joinpath("/abcdefgh", "/12345678", "/abcdefgh/12345678"); check_joinpath("/abcdefgh", "/12345678/", "/abcdefgh/12345678/"); check_joinpath("/abcdefgh/", "12345678/", "/abcdefgh/12345678/"); check_joinpath(REP1024("aaaa"), "", REP1024("aaaa") "/"); check_joinpath(REP1024("aaaa/"), "", REP1024("aaaa/")); check_joinpath(REP1024("/aaaa"), "", REP1024("/aaaa") "/"); check_joinpath(REP1024("aaaa"), REP1024("bbbb"), REP1024("aaaa") "/" REP1024("bbbb")); check_joinpath(REP1024("/aaaa"), REP1024("/bbbb"), REP1024("/aaaa") REP1024("/bbbb")); } /* properly join path components for more than one path */ void test_path__06_long_joins(void) { check_joinpath_n("", "", "", "", ""); check_joinpath_n("", "a", "", "", "a/"); check_joinpath_n("a", "", "", "", "a/"); check_joinpath_n("", "", "", "a", "a"); check_joinpath_n("a", "b", "", "/c/d/", "a/b/c/d/"); check_joinpath_n("a", "b", "", "/c/d", "a/b/c/d"); check_joinpath_n("abcd", "efgh", "ijkl", "mnop", "abcd/efgh/ijkl/mnop"); check_joinpath_n("abcd/", "efgh/", "ijkl/", "mnop/", "abcd/efgh/ijkl/mnop/"); check_joinpath_n("/abcd/", "/efgh/", "/ijkl/", "/mnop/", "/abcd/efgh/ijkl/mnop/"); check_joinpath_n(REP1024("a"), REP1024("b"), REP1024("c"), REP1024("d"), REP1024("a") "/" REP1024("b") "/" REP1024("c") "/" REP1024("d")); check_joinpath_n(REP1024("/a"), REP1024("/b"), REP1024("/c"), REP1024("/d"), REP1024("/a") REP1024("/b") REP1024("/c") REP1024("/d")); } static void check_path_to_dir( const char* path, const char* expected) { git_str tgt = GIT_STR_INIT; git_str_sets(&tgt, path); cl_git_pass(git_fs_path_to_dir(&tgt)); cl_assert_equal_s(expected, tgt.ptr); git_str_dispose(&tgt); } static void check_string_to_dir( const char* path, size_t maxlen, const char* expected) { size_t len = strlen(path); char *buf = git__malloc(len + 2); cl_assert(buf); strncpy(buf, path, len + 2); git_fs_path_string_to_dir(buf, maxlen); cl_assert_equal_s(expected, buf); git__free(buf); } /* convert paths to dirs */ void test_path__07_path_to_dir(void) { check_path_to_dir("", ""); check_path_to_dir(".", "./"); check_path_to_dir("./", "./"); check_path_to_dir("a/", "a/"); check_path_to_dir("ab", "ab/"); /* make sure we try just under and just over an expansion that will * require a realloc */ check_path_to_dir("abcdef", "abcdef/"); check_path_to_dir("abcdefg", "abcdefg/"); check_path_to_dir("abcdefgh", "abcdefgh/"); check_path_to_dir("abcdefghi", "abcdefghi/"); check_path_to_dir(REP1024("abcd") "/", REP1024("abcd") "/"); check_path_to_dir(REP1024("abcd"), REP1024("abcd") "/"); check_string_to_dir("", 1, ""); check_string_to_dir(".", 1, "."); check_string_to_dir(".", 2, "./"); check_string_to_dir(".", 3, "./"); check_string_to_dir("abcd", 3, "abcd"); check_string_to_dir("abcd", 4, "abcd"); check_string_to_dir("abcd", 5, "abcd/"); check_string_to_dir("abcd", 6, "abcd/"); } /* join path to itself */ void test_path__08_self_join(void) { git_str path = GIT_STR_INIT; size_t asize = 0; asize = path.asize; cl_git_pass(git_str_sets(&path, "/foo")); cl_assert_equal_s(path.ptr, "/foo"); cl_assert(asize < path.asize); asize = path.asize; cl_git_pass(git_str_joinpath(&path, path.ptr, "this is a new string")); cl_assert_equal_s(path.ptr, "/foo/this is a new string"); cl_assert(asize < path.asize); asize = path.asize; cl_git_pass(git_str_joinpath(&path, path.ptr, "/grow the buffer, grow the buffer, grow the buffer")); cl_assert_equal_s(path.ptr, "/foo/this is a new string/grow the buffer, grow the buffer, grow the buffer"); cl_assert(asize < path.asize); git_str_dispose(&path); cl_git_pass(git_str_sets(&path, "/foo/bar")); cl_git_pass(git_str_joinpath(&path, path.ptr + 4, "baz")); cl_assert_equal_s(path.ptr, "/bar/baz"); asize = path.asize; cl_git_pass(git_str_joinpath(&path, path.ptr + 4, "somethinglongenoughtorealloc")); cl_assert_equal_s(path.ptr, "/baz/somethinglongenoughtorealloc"); cl_assert(asize < path.asize); git_str_dispose(&path); } static void check_percent_decoding(const char *expected_result, const char *input) { git_str buf = GIT_STR_INIT; cl_git_pass(git__percent_decode(&buf, input)); cl_assert_equal_s(expected_result, git_str_cstr(&buf)); git_str_dispose(&buf); } void test_path__09_percent_decode(void) { check_percent_decoding("abcd", "abcd"); check_percent_decoding("a2%", "a2%"); check_percent_decoding("a2%3", "a2%3"); check_percent_decoding("a2%%3", "a2%%3"); check_percent_decoding("a2%3z", "a2%3z"); check_percent_decoding("a,", "a%2c"); check_percent_decoding("a21", "a2%31"); check_percent_decoding("a2%1", "a2%%31"); check_percent_decoding("a bc ", "a%20bc%20"); check_percent_decoding("Vicent Mart" "\355", "Vicent%20Mart%ED"); } static void check_fromurl(const char *expected_result, const char *input, int should_fail) { git_str buf = GIT_STR_INIT; assert(should_fail || expected_result); if (!should_fail) { cl_git_pass(git_fs_path_fromurl(&buf, input)); cl_assert_equal_s(expected_result, git_str_cstr(&buf)); } else cl_git_fail(git_fs_path_fromurl(&buf, input)); git_str_dispose(&buf); } #ifdef GIT_WIN32 #define ABS_PATH_MARKER "" #else #define ABS_PATH_MARKER "/" #endif void test_path__10_fromurl(void) { /* Failing cases */ check_fromurl(NULL, "a", 1); check_fromurl(NULL, "http:///c:/Temp%20folder/note.txt", 1); check_fromurl(NULL, "file://c:/Temp%20folder/note.txt", 1); check_fromurl(NULL, "file:////c:/Temp%20folder/note.txt", 1); check_fromurl(NULL, "file:///", 1); check_fromurl(NULL, "file:////", 1); check_fromurl(NULL, "file://servername/c:/Temp%20folder/note.txt", 1); /* Passing cases */ check_fromurl(ABS_PATH_MARKER "c:/Temp folder/note.txt", "file:///c:/Temp%20folder/note.txt", 0); check_fromurl(ABS_PATH_MARKER "c:/Temp folder/note.txt", "file://localhost/c:/Temp%20folder/note.txt", 0); check_fromurl(ABS_PATH_MARKER "c:/Temp+folder/note.txt", "file:///c:/Temp+folder/note.txt", 0); check_fromurl(ABS_PATH_MARKER "a", "file:///a", 0); } typedef struct { int expect_idx; int cancel_after; char **expect; } check_walkup_info; #define CANCEL_VALUE 1234 static int check_one_walkup_step(void *ref, const char *path) { check_walkup_info *info = (check_walkup_info *)ref; if (!info->cancel_after) { cl_assert_equal_s(info->expect[info->expect_idx], "[CANCEL]"); return CANCEL_VALUE; } info->cancel_after--; cl_assert(info->expect[info->expect_idx] != NULL); cl_assert_equal_s(info->expect[info->expect_idx], path); info->expect_idx++; return 0; } void test_path__11_walkup(void) { git_str p = GIT_STR_INIT; char *expect[] = { /* 1 */ "/a/b/c/d/e/", "/a/b/c/d/", "/a/b/c/", "/a/b/", "/a/", "/", NULL, /* 2 */ "/a/b/c/d/e", "/a/b/c/d/", "/a/b/c/", "/a/b/", "/a/", "/", NULL, /* 3 */ "/a/b/c/d/e", "/a/b/c/d/", "/a/b/c/", "/a/b/", "/a/", "/", NULL, /* 4 */ "/a/b/c/d/e", "/a/b/c/d/", "/a/b/c/", "/a/b/", "/a/", "/", NULL, /* 5 */ "/a/b/c/d/e", "/a/b/c/d/", "/a/b/c/", "/a/b/", NULL, /* 6 */ "/a/b/c/d/e", "/a/b/c/d/", "/a/b/c/", "/a/b/", NULL, /* 7 */ "this_is_a_path", "", NULL, /* 8 */ "this_is_a_path/", "", NULL, /* 9 */ "///a///b///c///d///e///", "///a///b///c///d///", "///a///b///c///", "///a///b///", "///a///", "///", NULL, /* 10 */ "a/b/c/", "a/b/", "a/", "", NULL, /* 11 */ "a/b/c", "a/b/", "a/", "", NULL, /* 12 */ "a/b/c/", "a/b/", "a/", NULL, /* 13 */ "", NULL, /* 14 */ "/", NULL, /* 15 */ NULL }; char *root[] = { /* 1 */ NULL, /* 2 */ NULL, /* 3 */ "/", /* 4 */ "", /* 5 */ "/a/b", /* 6 */ "/a/b/", /* 7 */ NULL, /* 8 */ NULL, /* 9 */ NULL, /* 10 */ NULL, /* 11 */ NULL, /* 12 */ "a/", /* 13 */ NULL, /* 14 */ NULL, }; int i, j; check_walkup_info info; info.expect = expect; info.cancel_after = -1; for (i = 0, j = 0; expect[i] != NULL; i++, j++) { git_str_sets(&p, expect[i]); info.expect_idx = i; cl_git_pass( git_fs_path_walk_up(&p, root[j], check_one_walkup_step, &info) ); cl_assert_equal_s(p.ptr, expect[i]); cl_assert(expect[info.expect_idx] == NULL); i = info.expect_idx; } git_str_dispose(&p); } void test_path__11a_walkup_cancel(void) { git_str p = GIT_STR_INIT; int cancel[] = { 3, 2, 1, 0 }; char *expect[] = { "/a/b/c/d/e/", "/a/b/c/d/", "/a/b/c/", "[CANCEL]", NULL, "/a/b/c/d/e", "/a/b/c/d/", "[CANCEL]", NULL, "/a/b/c/d/e", "[CANCEL]", NULL, "[CANCEL]", NULL, NULL }; char *root[] = { NULL, NULL, "/", "", NULL }; int i, j; check_walkup_info info; info.expect = expect; for (i = 0, j = 0; expect[i] != NULL; i++, j++) { git_str_sets(&p, expect[i]); info.cancel_after = cancel[j]; info.expect_idx = i; cl_assert_equal_i( CANCEL_VALUE, git_fs_path_walk_up(&p, root[j], check_one_walkup_step, &info) ); /* skip to next run of expectations */ while (expect[i] != NULL) i++; } git_str_dispose(&p); } void test_path__12_offset_to_path_root(void) { cl_assert(git_fs_path_root("non/rooted/path") == -1); cl_assert(git_fs_path_root("/rooted/path") == 0); #ifdef GIT_WIN32 /* Windows specific tests */ cl_assert(git_fs_path_root("C:non/rooted/path") == -1); cl_assert(git_fs_path_root("C:/rooted/path") == 2); cl_assert(git_fs_path_root("//computername/sharefolder/resource") == 14); cl_assert(git_fs_path_root("//computername/sharefolder") == 14); cl_assert(git_fs_path_root("//computername") == -1); #endif } #define NON_EXISTING_FILEPATH "i_hope_i_do_not_exist" void test_path__13_cannot_prettify_a_non_existing_file(void) { git_str p = GIT_STR_INIT; cl_assert_equal_b(git_fs_path_exists(NON_EXISTING_FILEPATH), false); cl_assert_equal_i(GIT_ENOTFOUND, git_fs_path_prettify(&p, NON_EXISTING_FILEPATH, NULL)); cl_assert_equal_i(GIT_ENOTFOUND, git_fs_path_prettify(&p, NON_EXISTING_FILEPATH "/so-do-i", NULL)); git_str_dispose(&p); } void test_path__14_apply_relative(void) { git_str p = GIT_STR_INIT; cl_git_pass(git_str_sets(&p, "/this/is/a/base")); cl_git_pass(git_fs_path_apply_relative(&p, "../test")); cl_assert_equal_s("/this/is/a/test", p.ptr); cl_git_pass(git_fs_path_apply_relative(&p, "../../the/./end")); cl_assert_equal_s("/this/is/the/end", p.ptr); cl_git_pass(git_fs_path_apply_relative(&p, "./of/this/../the/string")); cl_assert_equal_s("/this/is/the/end/of/the/string", p.ptr); cl_git_pass(git_fs_path_apply_relative(&p, "../../../../../..")); cl_assert_equal_s("/this/", p.ptr); cl_git_pass(git_fs_path_apply_relative(&p, "../")); cl_assert_equal_s("/", p.ptr); cl_git_fail(git_fs_path_apply_relative(&p, "../../..")); cl_git_pass(git_str_sets(&p, "d:/another/test")); cl_git_pass(git_fs_path_apply_relative(&p, "../..")); cl_assert_equal_s("d:/", p.ptr); cl_git_pass(git_fs_path_apply_relative(&p, "from/here/to/../and/./back/.")); cl_assert_equal_s("d:/from/here/and/back/", p.ptr); cl_git_pass(git_str_sets(&p, "https://my.url.com/test.git")); cl_git_pass(git_fs_path_apply_relative(&p, "../another.git")); cl_assert_equal_s("https://my.url.com/another.git", p.ptr); cl_git_pass(git_fs_path_apply_relative(&p, "../full/path/url.patch")); cl_assert_equal_s("https://my.url.com/full/path/url.patch", p.ptr); cl_git_pass(git_fs_path_apply_relative(&p, "..")); cl_assert_equal_s("https://my.url.com/full/path/", p.ptr); cl_git_pass(git_fs_path_apply_relative(&p, "../../../")); cl_assert_equal_s("https://", p.ptr); cl_git_pass(git_str_sets(&p, "../../this/is/relative")); cl_git_pass(git_fs_path_apply_relative(&p, "../../preserves/the/prefix")); cl_assert_equal_s("../../this/preserves/the/prefix", p.ptr); cl_git_pass(git_fs_path_apply_relative(&p, "../../../../that")); cl_assert_equal_s("../../that", p.ptr); cl_git_pass(git_fs_path_apply_relative(&p, "../there")); cl_assert_equal_s("../../there", p.ptr); git_str_dispose(&p); } static void assert_resolve_relative( git_str *buf, const char *expected, const char *path) { cl_git_pass(git_str_sets(buf, path)); cl_git_pass(git_fs_path_resolve_relative(buf, 0)); cl_assert_equal_s(expected, buf->ptr); } void test_path__15_resolve_relative(void) { git_str buf = GIT_STR_INIT; assert_resolve_relative(&buf, "", ""); assert_resolve_relative(&buf, "", "."); assert_resolve_relative(&buf, "", "./"); assert_resolve_relative(&buf, "..", ".."); assert_resolve_relative(&buf, "../", "../"); assert_resolve_relative(&buf, "..", "./.."); assert_resolve_relative(&buf, "../", "./../"); assert_resolve_relative(&buf, "../", "../."); assert_resolve_relative(&buf, "../", ".././"); assert_resolve_relative(&buf, "../..", "../.."); assert_resolve_relative(&buf, "../../", "../../"); assert_resolve_relative(&buf, "/", "/"); assert_resolve_relative(&buf, "/", "/."); assert_resolve_relative(&buf, "", "a/.."); assert_resolve_relative(&buf, "", "a/../"); assert_resolve_relative(&buf, "", "a/../."); assert_resolve_relative(&buf, "/a", "/a"); assert_resolve_relative(&buf, "/a/", "/a/."); assert_resolve_relative(&buf, "/", "/a/../"); assert_resolve_relative(&buf, "/", "/a/../."); assert_resolve_relative(&buf, "/", "/a/.././"); assert_resolve_relative(&buf, "a", "a"); assert_resolve_relative(&buf, "a/", "a/"); assert_resolve_relative(&buf, "a/", "a/."); assert_resolve_relative(&buf, "a/", "a/./"); assert_resolve_relative(&buf, "a/b", "a//b"); assert_resolve_relative(&buf, "a/b/c", "a/b/c"); assert_resolve_relative(&buf, "b/c", "./b/c"); assert_resolve_relative(&buf, "a/c", "a/./c"); assert_resolve_relative(&buf, "a/b/", "a/b/."); assert_resolve_relative(&buf, "/a/b/c", "///a/b/c"); assert_resolve_relative(&buf, "/", "////"); assert_resolve_relative(&buf, "/a", "///a"); assert_resolve_relative(&buf, "/", "///."); assert_resolve_relative(&buf, "/", "///a/.."); assert_resolve_relative(&buf, "../../path", "../../test//../././path"); assert_resolve_relative(&buf, "../d", "a/b/../../../c/../d"); cl_git_pass(git_str_sets(&buf, "/..")); cl_git_fail(git_fs_path_resolve_relative(&buf, 0)); cl_git_pass(git_str_sets(&buf, "/./..")); cl_git_fail(git_fs_path_resolve_relative(&buf, 0)); cl_git_pass(git_str_sets(&buf, "/.//..")); cl_git_fail(git_fs_path_resolve_relative(&buf, 0)); cl_git_pass(git_str_sets(&buf, "/../.")); cl_git_fail(git_fs_path_resolve_relative(&buf, 0)); cl_git_pass(git_str_sets(&buf, "/../.././../a")); cl_git_fail(git_fs_path_resolve_relative(&buf, 0)); cl_git_pass(git_str_sets(&buf, "////..")); cl_git_fail(git_fs_path_resolve_relative(&buf, 0)); /* things that start with Windows network paths */ #ifdef GIT_WIN32 assert_resolve_relative(&buf, "//a/b/c", "//a/b/c"); assert_resolve_relative(&buf, "//a/", "//a/b/.."); assert_resolve_relative(&buf, "//a/b/c", "//a/Q/../b/x/y/../../c"); cl_git_pass(git_str_sets(&buf, "//a/b/../..")); cl_git_fail(git_fs_path_resolve_relative(&buf, 0)); #else assert_resolve_relative(&buf, "/a/b/c", "//a/b/c"); assert_resolve_relative(&buf, "/a/", "//a/b/.."); assert_resolve_relative(&buf, "/a/b/c", "//a/Q/../b/x/y/../../c"); assert_resolve_relative(&buf, "/", "//a/b/../.."); #endif git_str_dispose(&buf); } #define assert_common_dirlen(i, p, q) \ cl_assert_equal_i((i), git_fs_path_common_dirlen((p), (q))); void test_path__16_resolve_relative(void) { assert_common_dirlen(0, "", ""); assert_common_dirlen(0, "", "bar.txt"); assert_common_dirlen(0, "foo.txt", "bar.txt"); assert_common_dirlen(0, "foo.txt", ""); assert_common_dirlen(0, "foo/bar.txt", "bar/foo.txt"); assert_common_dirlen(0, "foo/bar.txt", "../foo.txt"); assert_common_dirlen(1, "/one.txt", "/two.txt"); assert_common_dirlen(4, "foo/one.txt", "foo/two.txt"); assert_common_dirlen(5, "/foo/one.txt", "/foo/two.txt"); assert_common_dirlen(6, "a/b/c/foo.txt", "a/b/c/d/e/bar.txt"); assert_common_dirlen(7, "/a/b/c/foo.txt", "/a/b/c/d/e/bar.txt"); } static void fix_path(git_str *s) { #ifndef GIT_WIN32 GIT_UNUSED(s); #else char* c; for (c = s->ptr; *c; c++) { if (*c == '/') *c = '\\'; } #endif } void test_path__find_exe_in_path(void) { char *orig_path; git_str sandbox_path = GIT_STR_INIT; git_str new_path = GIT_STR_INIT, full_path = GIT_STR_INIT, dummy_path = GIT_STR_INIT; #ifdef GIT_WIN32 static const char *bogus_path_1 = "c:\\does\\not\\exist\\"; static const char *bogus_path_2 = "e:\\non\\existent"; #else static const char *bogus_path_1 = "/this/path/does/not/exist/"; static const char *bogus_path_2 = "/non/existent"; #endif orig_path = cl_getenv("PATH"); git_str_puts(&sandbox_path, clar_sandbox_path()); git_str_joinpath(&dummy_path, sandbox_path.ptr, "dummmmmmmy_libgit2_file"); cl_git_rewritefile(dummy_path.ptr, "this is a dummy file"); fix_path(&sandbox_path); fix_path(&dummy_path); cl_git_pass(git_str_printf(&new_path, "%s%c%s%c%s%c%s", bogus_path_1, GIT_PATH_LIST_SEPARATOR, orig_path, GIT_PATH_LIST_SEPARATOR, sandbox_path.ptr, GIT_PATH_LIST_SEPARATOR, bogus_path_2)); check_setenv("PATH", new_path.ptr); cl_git_fail_with(GIT_ENOTFOUND, git_fs_path_find_executable(&full_path, "this_file_does_not_exist")); cl_git_pass(git_fs_path_find_executable(&full_path, "dummmmmmmy_libgit2_file")); cl_assert_equal_s(full_path.ptr, dummy_path.ptr); git_str_dispose(&full_path); git_str_dispose(&new_path); git_str_dispose(&dummy_path); git_str_dispose(&sandbox_path); git__free(orig_path); } void test_path__validate_current_user_ownership(void) { bool is_cur; cl_must_pass(p_mkdir("testdir", 0777)); cl_git_pass(git_fs_path_owner_is_current_user(&is_cur, "testdir")); cl_assert_equal_i(is_cur, 1); cl_git_rewritefile("testfile", "This is a test file."); cl_git_pass(git_fs_path_owner_is_current_user(&is_cur, "testfile")); cl_assert_equal_i(is_cur, 1); #ifdef GIT_WIN32 cl_git_pass(git_fs_path_owner_is_current_user(&is_cur, "C:\\")); cl_assert_equal_i(is_cur, 0); cl_git_fail(git_fs_path_owner_is_current_user(&is_cur, "c:\\path\\does\\not\\exist")); #else cl_git_pass(git_fs_path_owner_is_current_user(&is_cur, "/")); cl_assert_equal_i(is_cur, 0); cl_git_fail(git_fs_path_owner_is_current_user(&is_cur, "/path/does/not/exist")); #endif }
libgit2-main
tests/util/path.c
#include "clar_libgit2.h" #include "pool.h" #include "git2/oid.h" void test_pool__0(void) { int i; git_pool p; void *ptr; git_pool_init(&p, 1); for (i = 1; i < 10000; i *= 2) { ptr = git_pool_malloc(&p, i); cl_assert(ptr != NULL); cl_assert(git_pool__ptr_in_pool(&p, ptr)); cl_assert(!git_pool__ptr_in_pool(&p, &i)); } git_pool_clear(&p); } void test_pool__1(void) { int i; git_pool p; git_pool_init(&p, 1); p.page_size = 4000; for (i = 2010; i > 0; i--) cl_assert(git_pool_malloc(&p, i) != NULL); #ifndef GIT_DEBUG_POOL /* with fixed page size, allocation must end up with these values */ cl_assert_equal_i(591, git_pool__open_pages(&p)); #endif git_pool_clear(&p); git_pool_init(&p, 1); p.page_size = 4120; for (i = 2010; i > 0; i--) cl_assert(git_pool_malloc(&p, i) != NULL); #ifndef GIT_DEBUG_POOL /* with fixed page size, allocation must end up with these values */ cl_assert_equal_i(sizeof(void *) == 8 ? 575 : 573, git_pool__open_pages(&p)); #endif git_pool_clear(&p); } void test_pool__strndup_limit(void) { git_pool p; git_pool_init(&p, 1); /* ensure 64 bit doesn't overflow */ cl_assert(git_pool_strndup(&p, "foo", (size_t)-1) == NULL); git_pool_clear(&p); }
libgit2-main
tests/util/pool.c
#include "clar_libgit2.h" #include "futils.h" #include "posix.h" void test_stat__initialize(void) { cl_git_pass(git_futils_mkdir("root/d1/d2", 0755, GIT_MKDIR_PATH)); cl_git_mkfile("root/file", "whatever\n"); cl_git_mkfile("root/d1/file", "whatever\n"); } void test_stat__cleanup(void) { git_futils_rmdir_r("root", NULL, GIT_RMDIR_REMOVE_FILES); } #define cl_assert_error(val) \ do { err = errno; cl_assert_equal_i((val), err); } while (0) void test_stat__0(void) { struct stat st; int err; cl_assert_equal_i(0, p_lstat("root", &st)); cl_assert(S_ISDIR(st.st_mode)); cl_assert_error(0); cl_assert_equal_i(0, p_lstat("root/", &st)); cl_assert(S_ISDIR(st.st_mode)); cl_assert_error(0); cl_assert_equal_i(0, p_lstat("root/file", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_error(0); cl_assert_equal_i(0, p_lstat("root/d1", &st)); cl_assert(S_ISDIR(st.st_mode)); cl_assert_error(0); cl_assert_equal_i(0, p_lstat("root/d1/", &st)); cl_assert(S_ISDIR(st.st_mode)); cl_assert_error(0); cl_assert_equal_i(0, p_lstat("root/d1/file", &st)); cl_assert(S_ISREG(st.st_mode)); cl_assert_error(0); cl_assert(p_lstat("root/missing", &st) < 0); cl_assert_error(ENOENT); cl_assert(p_lstat("root/missing/but/could/be/created", &st) < 0); cl_assert_error(ENOENT); cl_assert(p_lstat_posixly("root/missing/but/could/be/created", &st) < 0); cl_assert_error(ENOENT); cl_assert(p_lstat("root/d1/missing", &st) < 0); cl_assert_error(ENOENT); cl_assert(p_lstat("root/d1/missing/deeper/path", &st) < 0); cl_assert_error(ENOENT); cl_assert(p_lstat_posixly("root/d1/missing/deeper/path", &st) < 0); cl_assert_error(ENOENT); cl_assert(p_lstat_posixly("root/d1/file/deeper/path", &st) < 0); cl_assert_error(ENOTDIR); cl_assert(p_lstat("root/file/invalid", &st) < 0); #ifdef GIT_WIN32 cl_assert_error(ENOENT); #else cl_assert_error(ENOTDIR); #endif cl_assert(p_lstat_posixly("root/file/invalid", &st) < 0); cl_assert_error(ENOTDIR); cl_assert(p_lstat("root/file/invalid/deeper_path", &st) < 0); #ifdef GIT_WIN32 cl_assert_error(ENOENT); #else cl_assert_error(ENOTDIR); #endif cl_assert(p_lstat_posixly("root/file/invalid/deeper_path", &st) < 0); cl_assert_error(ENOTDIR); cl_assert(p_lstat_posixly("root/d1/file/extra", &st) < 0); cl_assert_error(ENOTDIR); cl_assert(p_lstat_posixly("root/d1/file/further/invalid/items", &st) < 0); cl_assert_error(ENOTDIR); } void test_stat__root(void) { const char *sandbox = clar_sandbox_path(); git_str root = GIT_STR_INIT; int root_len; struct stat st; root_len = git_fs_path_root(sandbox); cl_assert(root_len >= 0); git_str_set(&root, sandbox, root_len+1); cl_must_pass(p_stat(root.ptr, &st)); cl_assert(S_ISDIR(st.st_mode)); git_str_dispose(&root); }
libgit2-main
tests/util/stat.c
#include "clar_libgit2.h" #include "hash.h" #define FIXTURE_DIR "sha1" #ifdef GIT_SHA256_WIN32 static git_hash_win32_provider_t orig_provider; #endif void test_sha256__initialize(void) { #ifdef GIT_SHA256_WIN32 orig_provider = git_hash_win32_provider(); #endif cl_fixture_sandbox(FIXTURE_DIR); } void test_sha256__cleanup(void) { #ifdef GIT_SHA256_WIN32 git_hash_win32_set_provider(orig_provider); #endif cl_fixture_cleanup(FIXTURE_DIR); } static int sha256_file(unsigned char *out, const char *filename) { git_hash_ctx ctx; char buf[2048]; int fd, ret; ssize_t read_len; fd = p_open(filename, O_RDONLY); cl_assert(fd >= 0); cl_git_pass(git_hash_ctx_init(&ctx, GIT_HASH_ALGORITHM_SHA256)); while ((read_len = p_read(fd, buf, 2048)) > 0) cl_git_pass(git_hash_update(&ctx, buf, (size_t)read_len)); cl_assert_equal_i(0, read_len); p_close(fd); ret = git_hash_final(out, &ctx); git_hash_ctx_cleanup(&ctx); return ret; } void test_sha256__empty(void) { unsigned char expected[GIT_HASH_SHA256_SIZE] = { 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55 }; unsigned char actual[GIT_HASH_SHA256_SIZE]; cl_git_pass(sha256_file(actual, FIXTURE_DIR "/empty")); cl_assert_equal_i(0, memcmp(expected, actual, GIT_HASH_SHA256_SIZE)); } void test_sha256__hello(void) { unsigned char expected[GIT_HASH_SHA256_SIZE] = { 0xaa, 0x32, 0x7f, 0xae, 0x5c, 0x91, 0x58, 0x3a, 0x4f, 0xb6, 0x54, 0xcc, 0xb6, 0xc2, 0xb1, 0x0c, 0x77, 0xd7, 0x49, 0xc9, 0x91, 0x2a, 0x8d, 0x6b, 0x47, 0x26, 0x13, 0xc0, 0xa0, 0x4b, 0x4d, 0xad }; unsigned char actual[GIT_HASH_SHA256_SIZE]; cl_git_pass(sha256_file(actual, FIXTURE_DIR "/hello_c")); cl_assert_equal_i(0, memcmp(expected, actual, GIT_HASH_SHA256_SIZE)); } void test_sha256__pdf(void) { unsigned char expected[GIT_HASH_SHA256_SIZE] = { 0x2b, 0xb7, 0x87, 0xa7, 0x3e, 0x37, 0x35, 0x2f, 0x92, 0x38, 0x3a, 0xbe, 0x7e, 0x29, 0x02, 0x93, 0x6d, 0x10, 0x59, 0xad, 0x9f, 0x1b, 0xa6, 0xda, 0xaa, 0x9c, 0x1e, 0x58, 0xee, 0x69, 0x70, 0xd0 }; unsigned char actual[GIT_HASH_SHA256_SIZE]; cl_git_pass(sha256_file(actual, FIXTURE_DIR "/shattered-1.pdf")); cl_assert_equal_i(0, memcmp(expected, actual, GIT_HASH_SHA256_SIZE)); } void test_sha256__win32_providers(void) { #ifdef GIT_SHA256_WIN32 unsigned char expected[GIT_HASH_SHA256_SIZE] = { 0x2b, 0xb7, 0x87, 0xa7, 0x3e, 0x37, 0x35, 0x2f, 0x92, 0x38, 0x3a, 0xbe, 0x7e, 0x29, 0x02, 0x93, 0x6d, 0x10, 0x59, 0xad, 0x9f, 0x1b, 0xa6, 0xda, 0xaa, 0x9c, 0x1e, 0x58, 0xee, 0x69, 0x70, 0xd0 }; unsigned char actual[GIT_HASH_SHA256_SIZE]; git_hash_win32_set_provider(GIT_HASH_WIN32_CRYPTOAPI); cl_git_pass(sha256_file(actual, FIXTURE_DIR "/shattered-1.pdf")); cl_assert_equal_i(0, memcmp(expected, actual, GIT_HASH_SHA256_SIZE)); git_hash_win32_set_provider(GIT_HASH_WIN32_CNG); cl_git_pass(sha256_file(actual, FIXTURE_DIR "/shattered-1.pdf")); cl_assert_equal_i(0, memcmp(expected, actual, GIT_HASH_SHA256_SIZE)); #endif }
libgit2-main
tests/util/sha256.c
#include "clar_libgit2.h" #include "strmap.h" static git_strmap *g_table; void test_strmap__initialize(void) { cl_git_pass(git_strmap_new(&g_table)); cl_assert(g_table != NULL); } void test_strmap__cleanup(void) { git_strmap_free(g_table); } void test_strmap__0(void) { cl_assert(git_strmap_size(g_table) == 0); } static void insert_strings(git_strmap *table, size_t count) { size_t i, j, over; char *str; for (i = 0; i < count; ++i) { str = malloc(10); for (j = 0; j < 10; ++j) str[j] = 'a' + (i % 26); str[9] = '\0'; /* if > 26, then encode larger value in first letters */ for (j = 0, over = i / 26; over > 0; j++, over = over / 26) str[j] = 'A' + (over % 26); cl_git_pass(git_strmap_set(table, str, str)); } cl_assert_equal_i(git_strmap_size(table), count); } void test_strmap__inserted_strings_can_be_retrieved(void) { char *str; int i; insert_strings(g_table, 20); cl_assert(git_strmap_exists(g_table, "aaaaaaaaa")); cl_assert(git_strmap_exists(g_table, "ggggggggg")); cl_assert(!git_strmap_exists(g_table, "aaaaaaaab")); cl_assert(!git_strmap_exists(g_table, "abcdefghi")); i = 0; git_strmap_foreach_value(g_table, str, { i++; free(str); }); cl_assert(i == 20); } void test_strmap__deleted_entry_cannot_be_retrieved(void) { char *str; int i; insert_strings(g_table, 20); cl_assert(git_strmap_exists(g_table, "bbbbbbbbb")); str = git_strmap_get(g_table, "bbbbbbbbb"); cl_assert_equal_s(str, "bbbbbbbbb"); cl_git_pass(git_strmap_delete(g_table, "bbbbbbbbb")); free(str); cl_assert(!git_strmap_exists(g_table, "bbbbbbbbb")); i = 0; git_strmap_foreach_value(g_table, str, { i++; free(str); }); cl_assert_equal_i(i, 19); } void test_strmap__inserting_many_keys_succeeds(void) { char *str; int i; insert_strings(g_table, 10000); i = 0; git_strmap_foreach_value(g_table, str, { i++; free(str); }); cl_assert_equal_i(i, 10000); } void test_strmap__get_succeeds_with_existing_entries(void) { const char *keys[] = { "foo", "bar", "gobble" }; char *values[] = { "oof", "rab", "elbbog" }; size_t i; for (i = 0; i < ARRAY_SIZE(keys); i++) cl_git_pass(git_strmap_set(g_table, keys[i], values[i])); cl_assert_equal_s(git_strmap_get(g_table, "foo"), "oof"); cl_assert_equal_s(git_strmap_get(g_table, "bar"), "rab"); cl_assert_equal_s(git_strmap_get(g_table, "gobble"), "elbbog"); } void test_strmap__get_returns_null_on_nonexisting_key(void) { const char *keys[] = { "foo", "bar", "gobble" }; char *values[] = { "oof", "rab", "elbbog" }; size_t i; for (i = 0; i < ARRAY_SIZE(keys); i++) cl_git_pass(git_strmap_set(g_table, keys[i], values[i])); cl_assert_equal_p(git_strmap_get(g_table, "other"), NULL); } void test_strmap__set_persists_key(void) { cl_git_pass(git_strmap_set(g_table, "foo", "oof")); cl_assert_equal_s(git_strmap_get(g_table, "foo"), "oof"); } void test_strmap__set_persists_multpile_keys(void) { cl_git_pass(git_strmap_set(g_table, "foo", "oof")); cl_git_pass(git_strmap_set(g_table, "bar", "rab")); cl_assert_equal_s(git_strmap_get(g_table, "foo"), "oof"); cl_assert_equal_s(git_strmap_get(g_table, "bar"), "rab"); } void test_strmap__set_updates_existing_key(void) { cl_git_pass(git_strmap_set(g_table, "foo", "oof")); cl_git_pass(git_strmap_set(g_table, "bar", "rab")); cl_git_pass(git_strmap_set(g_table, "gobble", "elbbog")); cl_assert_equal_i(git_strmap_size(g_table), 3); cl_git_pass(git_strmap_set(g_table, "foo", "other")); cl_assert_equal_i(git_strmap_size(g_table), 3); cl_assert_equal_s(git_strmap_get(g_table, "foo"), "other"); } void test_strmap__iteration(void) { struct { char *key; char *value; int seen; } entries[] = { { "foo", "oof" }, { "bar", "rab" }, { "gobble", "elbbog" }, }; const char *key, *value; size_t i, n; for (i = 0; i < ARRAY_SIZE(entries); i++) cl_git_pass(git_strmap_set(g_table, entries[i].key, entries[i].value)); i = 0, n = 0; while (git_strmap_iterate((void **) &value, g_table, &i, &key) == 0) { size_t j; for (j = 0; j < ARRAY_SIZE(entries); j++) { if (strcmp(entries[j].key, key)) continue; cl_assert_equal_i(entries[j].seen, 0); cl_assert_equal_s(entries[j].value, value); entries[j].seen++; break; } n++; } for (i = 0; i < ARRAY_SIZE(entries); i++) cl_assert_equal_i(entries[i].seen, 1); cl_assert_equal_i(n, ARRAY_SIZE(entries)); } void test_strmap__iterating_empty_map_stops_immediately(void) { size_t i = 0; cl_git_fail_with(git_strmap_iterate(NULL, g_table, &i, NULL), GIT_ITEROVER); }
libgit2-main
tests/util/strmap.c
#include "clar_libgit2.h" #include "futils.h" static const char *empty_tmp_dir = "test_gitfo_rmdir_recurs_test"; void test_rmdir__initialize(void) { git_str path = GIT_STR_INIT; cl_must_pass(p_mkdir(empty_tmp_dir, 0777)); cl_git_pass(git_str_joinpath(&path, empty_tmp_dir, "/one")); cl_must_pass(p_mkdir(path.ptr, 0777)); cl_git_pass(git_str_joinpath(&path, empty_tmp_dir, "/one/two_one")); cl_must_pass(p_mkdir(path.ptr, 0777)); cl_git_pass(git_str_joinpath(&path, empty_tmp_dir, "/one/two_two")); cl_must_pass(p_mkdir(path.ptr, 0777)); cl_git_pass(git_str_joinpath(&path, empty_tmp_dir, "/one/two_two/three")); cl_must_pass(p_mkdir(path.ptr, 0777)); cl_git_pass(git_str_joinpath(&path, empty_tmp_dir, "/two")); cl_must_pass(p_mkdir(path.ptr, 0777)); git_str_dispose(&path); } void test_rmdir__cleanup(void) { if (git_fs_path_exists(empty_tmp_dir)) cl_git_pass(git_futils_rmdir_r(empty_tmp_dir, NULL, GIT_RMDIR_REMOVE_FILES)); } /* make sure empty dir can be deleted recursively */ void test_rmdir__delete_recursive(void) { git_str path = GIT_STR_INIT; cl_git_pass(git_str_joinpath(&path, empty_tmp_dir, "/one")); cl_assert(git_fs_path_exists(git_str_cstr(&path))); cl_git_pass(git_futils_rmdir_r(empty_tmp_dir, NULL, GIT_RMDIR_EMPTY_HIERARCHY)); cl_assert(!git_fs_path_exists(git_str_cstr(&path))); git_str_dispose(&path); } /* make sure non-empty dir cannot be deleted recursively */ void test_rmdir__fail_to_delete_non_empty_dir(void) { git_str file = GIT_STR_INIT; cl_git_pass(git_str_joinpath(&file, empty_tmp_dir, "/two/file.txt")); cl_git_mkfile(git_str_cstr(&file), "dummy"); cl_git_fail(git_futils_rmdir_r(empty_tmp_dir, NULL, GIT_RMDIR_EMPTY_HIERARCHY)); cl_must_pass(p_unlink(file.ptr)); cl_git_pass(git_futils_rmdir_r(empty_tmp_dir, NULL, GIT_RMDIR_EMPTY_HIERARCHY)); cl_assert(!git_fs_path_exists(empty_tmp_dir)); git_str_dispose(&file); } void test_rmdir__keep_base(void) { cl_git_pass(git_futils_rmdir_r(empty_tmp_dir, NULL, GIT_RMDIR_SKIP_ROOT)); cl_assert(git_fs_path_exists(empty_tmp_dir)); } void test_rmdir__can_skip_non_empty_dir(void) { git_str file = GIT_STR_INIT; cl_git_pass(git_str_joinpath(&file, empty_tmp_dir, "/two/file.txt")); cl_git_mkfile(git_str_cstr(&file), "dummy"); cl_git_pass(git_futils_rmdir_r(empty_tmp_dir, NULL, GIT_RMDIR_SKIP_NONEMPTY)); cl_assert(git_fs_path_exists(git_str_cstr(&file)) == true); cl_git_pass(git_futils_rmdir_r(empty_tmp_dir, NULL, GIT_RMDIR_REMOVE_FILES)); cl_assert(git_fs_path_exists(empty_tmp_dir) == false); git_str_dispose(&file); } void test_rmdir__can_remove_empty_parents(void) { git_str file = GIT_STR_INIT; cl_git_pass( git_str_joinpath(&file, empty_tmp_dir, "/one/two_two/three/file.txt")); cl_git_mkfile(git_str_cstr(&file), "dummy"); cl_assert(git_fs_path_isfile(git_str_cstr(&file))); cl_git_pass(git_futils_rmdir_r("one/two_two/three/file.txt", empty_tmp_dir, GIT_RMDIR_REMOVE_FILES | GIT_RMDIR_EMPTY_PARENTS)); cl_assert(!git_fs_path_exists(git_str_cstr(&file))); git_str_rtruncate_at_char(&file, '/'); /* three (only contained file.txt) */ cl_assert(!git_fs_path_exists(git_str_cstr(&file))); git_str_rtruncate_at_char(&file, '/'); /* two_two (only contained three) */ cl_assert(!git_fs_path_exists(git_str_cstr(&file))); git_str_rtruncate_at_char(&file, '/'); /* one (contained two_one also) */ cl_assert(git_fs_path_exists(git_str_cstr(&file))); cl_assert(git_fs_path_exists(empty_tmp_dir) == true); git_str_dispose(&file); cl_git_pass(git_futils_rmdir_r(empty_tmp_dir, NULL, GIT_RMDIR_EMPTY_HIERARCHY)); }
libgit2-main
tests/util/rmdir.c
#include "clar_libgit2.h" static void assert_found(const char *haystack, const char *needle, size_t expected_pos) { cl_assert_equal_p(git__memmem(haystack, haystack ? strlen(haystack) : 0, needle, needle ? strlen(needle) : 0), haystack + expected_pos); } static void assert_absent(const char *haystack, const char *needle) { cl_assert_equal_p(git__memmem(haystack, haystack ? strlen(haystack) : 0, needle, needle ? strlen(needle) : 0), NULL); } void test_memmem__found(void) { assert_found("a", "a", 0); assert_found("ab", "a", 0); assert_found("ba", "a", 1); assert_found("aa", "a", 0); assert_found("aab", "aa", 0); assert_found("baa", "aa", 1); assert_found("dabc", "abc", 1); assert_found("abababc", "abc", 4); } void test_memmem__absent(void) { assert_absent("a", "b"); assert_absent("a", "aa"); assert_absent("ba", "ab"); assert_absent("ba", "ab"); assert_absent("abc", "abcd"); assert_absent("abcabcabc", "bcac"); } void test_memmem__edgecases(void) { assert_absent(NULL, NULL); assert_absent("a", NULL); assert_absent(NULL, "a"); assert_absent("", "a"); assert_absent("a", ""); }
libgit2-main
tests/util/memmem.c
#include "clar_libgit2.h" #include "sortedcache.h" static int name_only_cmp(const void *a, const void *b) { return strcmp(a, b); } void test_sortedcache__name_only(void) { git_sortedcache *sc; void *item; size_t pos; cl_git_pass(git_sortedcache_new( &sc, 0, NULL, NULL, name_only_cmp, NULL)); cl_git_pass(git_sortedcache_wlock(sc)); cl_git_pass(git_sortedcache_upsert(&item, sc, "aaa")); cl_git_pass(git_sortedcache_upsert(&item, sc, "bbb")); cl_git_pass(git_sortedcache_upsert(&item, sc, "zzz")); cl_git_pass(git_sortedcache_upsert(&item, sc, "mmm")); cl_git_pass(git_sortedcache_upsert(&item, sc, "iii")); git_sortedcache_wunlock(sc); cl_assert_equal_sz(5, git_sortedcache_entrycount(sc)); cl_assert((item = git_sortedcache_lookup(sc, "aaa")) != NULL); cl_assert_equal_s("aaa", item); cl_assert((item = git_sortedcache_lookup(sc, "mmm")) != NULL); cl_assert_equal_s("mmm", item); cl_assert((item = git_sortedcache_lookup(sc, "zzz")) != NULL); cl_assert_equal_s("zzz", item); cl_assert(git_sortedcache_lookup(sc, "qqq") == NULL); cl_assert((item = git_sortedcache_entry(sc, 0)) != NULL); cl_assert_equal_s("aaa", item); cl_assert((item = git_sortedcache_entry(sc, 1)) != NULL); cl_assert_equal_s("bbb", item); cl_assert((item = git_sortedcache_entry(sc, 2)) != NULL); cl_assert_equal_s("iii", item); cl_assert((item = git_sortedcache_entry(sc, 3)) != NULL); cl_assert_equal_s("mmm", item); cl_assert((item = git_sortedcache_entry(sc, 4)) != NULL); cl_assert_equal_s("zzz", item); cl_assert(git_sortedcache_entry(sc, 5) == NULL); cl_git_pass(git_sortedcache_lookup_index(&pos, sc, "aaa")); cl_assert_equal_sz(0, pos); cl_git_pass(git_sortedcache_lookup_index(&pos, sc, "iii")); cl_assert_equal_sz(2, pos); cl_git_pass(git_sortedcache_lookup_index(&pos, sc, "zzz")); cl_assert_equal_sz(4, pos); cl_assert_equal_i( GIT_ENOTFOUND, git_sortedcache_lookup_index(&pos, sc, "abc")); cl_git_pass(git_sortedcache_clear(sc, true)); cl_assert_equal_sz(0, git_sortedcache_entrycount(sc)); cl_assert(git_sortedcache_entry(sc, 0) == NULL); cl_assert(git_sortedcache_lookup(sc, "aaa") == NULL); cl_assert(git_sortedcache_entry(sc, 0) == NULL); git_sortedcache_free(sc); } typedef struct { int value; char smaller_value; char path[GIT_FLEX_ARRAY]; } sortedcache_test_struct; static int sortedcache_test_struct_cmp(const void *a_, const void *b_) { const sortedcache_test_struct *a = a_, *b = b_; return strcmp(a->path, b->path); } static void sortedcache_test_struct_free(void *payload, void *item_) { sortedcache_test_struct *item = item_; int *count = payload; (*count)++; item->smaller_value = 0; } void test_sortedcache__in_memory(void) { git_sortedcache *sc; sortedcache_test_struct *item; int free_count = 0; cl_git_pass(git_sortedcache_new( &sc, offsetof(sortedcache_test_struct, path), sortedcache_test_struct_free, &free_count, sortedcache_test_struct_cmp, NULL)); cl_git_pass(git_sortedcache_wlock(sc)); cl_git_pass(git_sortedcache_upsert((void **)&item, sc, "aaa")); item->value = 10; item->smaller_value = 1; cl_git_pass(git_sortedcache_upsert((void **)&item, sc, "bbb")); item->value = 20; item->smaller_value = 2; cl_git_pass(git_sortedcache_upsert((void **)&item, sc, "zzz")); item->value = 30; item->smaller_value = 26; cl_git_pass(git_sortedcache_upsert((void **)&item, sc, "mmm")); item->value = 40; item->smaller_value = 14; cl_git_pass(git_sortedcache_upsert((void **)&item, sc, "iii")); item->value = 50; item->smaller_value = 9; git_sortedcache_wunlock(sc); cl_assert_equal_sz(5, git_sortedcache_entrycount(sc)); cl_git_pass(git_sortedcache_rlock(sc)); cl_assert((item = git_sortedcache_lookup(sc, "aaa")) != NULL); cl_assert_equal_s("aaa", item->path); cl_assert_equal_i(10, item->value); cl_assert((item = git_sortedcache_lookup(sc, "mmm")) != NULL); cl_assert_equal_s("mmm", item->path); cl_assert_equal_i(40, item->value); cl_assert((item = git_sortedcache_lookup(sc, "zzz")) != NULL); cl_assert_equal_s("zzz", item->path); cl_assert_equal_i(30, item->value); cl_assert(git_sortedcache_lookup(sc, "abc") == NULL); /* not on Windows: * cl_git_pass(git_sortedcache_rlock(sc)); -- grab more than one */ cl_assert((item = git_sortedcache_entry(sc, 0)) != NULL); cl_assert_equal_s("aaa", item->path); cl_assert_equal_i(10, item->value); cl_assert((item = git_sortedcache_entry(sc, 1)) != NULL); cl_assert_equal_s("bbb", item->path); cl_assert_equal_i(20, item->value); cl_assert((item = git_sortedcache_entry(sc, 2)) != NULL); cl_assert_equal_s("iii", item->path); cl_assert_equal_i(50, item->value); cl_assert((item = git_sortedcache_entry(sc, 3)) != NULL); cl_assert_equal_s("mmm", item->path); cl_assert_equal_i(40, item->value); cl_assert((item = git_sortedcache_entry(sc, 4)) != NULL); cl_assert_equal_s("zzz", item->path); cl_assert_equal_i(30, item->value); cl_assert(git_sortedcache_entry(sc, 5) == NULL); git_sortedcache_runlock(sc); /* git_sortedcache_runlock(sc); */ cl_assert_equal_i(0, free_count); cl_git_pass(git_sortedcache_clear(sc, true)); cl_assert_equal_i(5, free_count); cl_assert_equal_sz(0, git_sortedcache_entrycount(sc)); cl_assert(git_sortedcache_entry(sc, 0) == NULL); cl_assert(git_sortedcache_lookup(sc, "aaa") == NULL); cl_assert(git_sortedcache_entry(sc, 0) == NULL); free_count = 0; cl_git_pass(git_sortedcache_wlock(sc)); cl_git_pass(git_sortedcache_upsert((void **)&item, sc, "testing")); item->value = 10; item->smaller_value = 3; cl_git_pass(git_sortedcache_upsert((void **)&item, sc, "again")); item->value = 20; item->smaller_value = 1; cl_git_pass(git_sortedcache_upsert((void **)&item, sc, "final")); item->value = 30; item->smaller_value = 2; git_sortedcache_wunlock(sc); cl_assert_equal_sz(3, git_sortedcache_entrycount(sc)); cl_assert((item = git_sortedcache_lookup(sc, "testing")) != NULL); cl_assert_equal_s("testing", item->path); cl_assert_equal_i(10, item->value); cl_assert((item = git_sortedcache_lookup(sc, "again")) != NULL); cl_assert_equal_s("again", item->path); cl_assert_equal_i(20, item->value); cl_assert((item = git_sortedcache_lookup(sc, "final")) != NULL); cl_assert_equal_s("final", item->path); cl_assert_equal_i(30, item->value); cl_assert(git_sortedcache_lookup(sc, "zzz") == NULL); cl_assert((item = git_sortedcache_entry(sc, 0)) != NULL); cl_assert_equal_s("again", item->path); cl_assert_equal_i(20, item->value); cl_assert((item = git_sortedcache_entry(sc, 1)) != NULL); cl_assert_equal_s("final", item->path); cl_assert_equal_i(30, item->value); cl_assert((item = git_sortedcache_entry(sc, 2)) != NULL); cl_assert_equal_s("testing", item->path); cl_assert_equal_i(10, item->value); cl_assert(git_sortedcache_entry(sc, 3) == NULL); { size_t pos; cl_git_pass(git_sortedcache_wlock(sc)); cl_git_pass(git_sortedcache_lookup_index(&pos, sc, "again")); cl_assert_equal_sz(0, pos); cl_git_pass(git_sortedcache_remove(sc, pos)); cl_assert_equal_i( GIT_ENOTFOUND, git_sortedcache_lookup_index(&pos, sc, "again")); cl_assert_equal_sz(2, git_sortedcache_entrycount(sc)); cl_git_pass(git_sortedcache_lookup_index(&pos, sc, "testing")); cl_assert_equal_sz(1, pos); cl_git_pass(git_sortedcache_remove(sc, pos)); cl_assert_equal_i( GIT_ENOTFOUND, git_sortedcache_lookup_index(&pos, sc, "testing")); cl_assert_equal_sz(1, git_sortedcache_entrycount(sc)); cl_git_pass(git_sortedcache_lookup_index(&pos, sc, "final")); cl_assert_equal_sz(0, pos); cl_git_pass(git_sortedcache_remove(sc, pos)); cl_assert_equal_i( GIT_ENOTFOUND, git_sortedcache_lookup_index(&pos, sc, "final")); cl_assert_equal_sz(0, git_sortedcache_entrycount(sc)); git_sortedcache_wunlock(sc); } git_sortedcache_free(sc); cl_assert_equal_i(3, free_count); } static void sortedcache_test_reload(git_sortedcache *sc) { int count = 0; git_str buf = GIT_STR_INIT; char *scan, *after; sortedcache_test_struct *item; cl_assert(git_sortedcache_lockandload(sc, &buf) > 0); cl_git_pass(git_sortedcache_clear(sc, false)); /* clear once we already have lock */ for (scan = buf.ptr; *scan; scan = after + 1) { int val = strtol(scan, &after, 0); cl_assert(after > scan); scan = after; for (scan = after; git__isspace(*scan); ++scan) /* find start */; for (after = scan; *after && *after != '\n'; ++after) /* find eol */; *after = '\0'; cl_git_pass(git_sortedcache_upsert((void **)&item, sc, scan)); item->value = val; item->smaller_value = (char)(count++); } git_sortedcache_wunlock(sc); git_str_dispose(&buf); } void test_sortedcache__on_disk(void) { git_sortedcache *sc; sortedcache_test_struct *item; int free_count = 0; size_t pos; cl_git_mkfile("cacheitems.txt", "10 abc\n20 bcd\n30 cde\n"); cl_git_pass(git_sortedcache_new( &sc, offsetof(sortedcache_test_struct, path), sortedcache_test_struct_free, &free_count, sortedcache_test_struct_cmp, "cacheitems.txt")); /* should need to reload the first time */ sortedcache_test_reload(sc); /* test what we loaded */ cl_assert_equal_sz(3, git_sortedcache_entrycount(sc)); cl_assert((item = git_sortedcache_lookup(sc, "abc")) != NULL); cl_assert_equal_s("abc", item->path); cl_assert_equal_i(10, item->value); cl_assert((item = git_sortedcache_lookup(sc, "cde")) != NULL); cl_assert_equal_s("cde", item->path); cl_assert_equal_i(30, item->value); cl_assert(git_sortedcache_lookup(sc, "aaa") == NULL); cl_assert((item = git_sortedcache_entry(sc, 0)) != NULL); cl_assert_equal_s("abc", item->path); cl_assert_equal_i(10, item->value); cl_assert((item = git_sortedcache_entry(sc, 1)) != NULL); cl_assert_equal_s("bcd", item->path); cl_assert_equal_i(20, item->value); cl_assert(git_sortedcache_entry(sc, 3) == NULL); /* should not need to reload this time */ cl_assert_equal_i(0, git_sortedcache_lockandload(sc, NULL)); /* rewrite ondisk file and reload */ cl_assert_equal_i(0, free_count); cl_git_rewritefile( "cacheitems.txt", "100 abc\n200 zzz\n500 aaa\n10 final\n"); sortedcache_test_reload(sc); cl_assert_equal_i(3, free_count); /* test what we loaded */ cl_assert_equal_sz(4, git_sortedcache_entrycount(sc)); cl_assert((item = git_sortedcache_lookup(sc, "abc")) != NULL); cl_assert_equal_s("abc", item->path); cl_assert_equal_i(100, item->value); cl_assert((item = git_sortedcache_lookup(sc, "final")) != NULL); cl_assert_equal_s("final", item->path); cl_assert_equal_i(10, item->value); cl_assert(git_sortedcache_lookup(sc, "cde") == NULL); cl_assert((item = git_sortedcache_entry(sc, 0)) != NULL); cl_assert_equal_s("aaa", item->path); cl_assert_equal_i(500, item->value); cl_assert((item = git_sortedcache_entry(sc, 2)) != NULL); cl_assert_equal_s("final", item->path); cl_assert_equal_i(10, item->value); cl_assert((item = git_sortedcache_entry(sc, 3)) != NULL); cl_assert_equal_s("zzz", item->path); cl_assert_equal_i(200, item->value); cl_git_pass(git_sortedcache_lookup_index(&pos, sc, "aaa")); cl_assert_equal_sz(0, pos); cl_git_pass(git_sortedcache_lookup_index(&pos, sc, "abc")); cl_assert_equal_sz(1, pos); cl_git_pass(git_sortedcache_lookup_index(&pos, sc, "final")); cl_assert_equal_sz(2, pos); cl_git_pass(git_sortedcache_lookup_index(&pos, sc, "zzz")); cl_assert_equal_sz(3, pos); cl_assert_equal_i( GIT_ENOTFOUND, git_sortedcache_lookup_index(&pos, sc, "missing")); cl_assert_equal_i( GIT_ENOTFOUND, git_sortedcache_lookup_index(&pos, sc, "cde")); git_sortedcache_free(sc); cl_assert_equal_i(7, free_count); }
libgit2-main
tests/util/sortedcache.c
#include "clar_libgit2.h" #include "varint.h" void test_encoding__decode(void) { const unsigned char *buf = (unsigned char *)"AB"; size_t size; cl_assert(git_decode_varint(buf, &size) == 65); cl_assert(size == 1); buf = (unsigned char *)"\xfe\xdc\xbaXY"; cl_assert(git_decode_varint(buf, &size) == 267869656); cl_assert(size == 4); buf = (unsigned char *)"\xaa\xaa\xfe\xdc\xbaXY"; cl_assert(git_decode_varint(buf, &size) == UINT64_C(1489279344088)); cl_assert(size == 6); buf = (unsigned char *)"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xfe\xdc\xbaXY"; cl_assert(git_decode_varint(buf, &size) == 0); cl_assert(size == 0); } void test_encoding__encode(void) { unsigned char buf[100]; cl_assert(git_encode_varint(buf, 100, 65) == 1); cl_assert(buf[0] == 'A'); cl_assert(git_encode_varint(buf, 1, 1) == 1); cl_assert(!memcmp(buf, "\x01", 1)); cl_assert(git_encode_varint(buf, 100, 267869656) == 4); cl_assert(!memcmp(buf, "\xfe\xdc\xbaX", 4)); cl_assert(git_encode_varint(buf, 100, UINT64_C(1489279344088)) == 6); cl_assert(!memcmp(buf, "\xaa\xaa\xfe\xdc\xbaX", 6)); cl_assert(git_encode_varint(buf, 1, UINT64_C(1489279344088)) == -1); }
libgit2-main
tests/util/encoding.c
#include "clar_libgit2.h" void test_errors__public_api(void) { char *str_in_error; git_error_clear(); cl_assert(git_error_last() == NULL); git_error_set_oom(); cl_assert(git_error_last() != NULL); cl_assert(git_error_last()->klass == GIT_ERROR_NOMEMORY); str_in_error = strstr(git_error_last()->message, "memory"); cl_assert(str_in_error != NULL); git_error_clear(); git_error_set_str(GIT_ERROR_REPOSITORY, "This is a test"); cl_assert(git_error_last() != NULL); str_in_error = strstr(git_error_last()->message, "This is a test"); cl_assert(str_in_error != NULL); git_error_clear(); cl_assert(git_error_last() == NULL); } #include "common.h" #include "util.h" #include "posix.h" void test_errors__new_school(void) { char *str_in_error; git_error_clear(); cl_assert(git_error_last() == NULL); git_error_set_oom(); /* internal fn */ cl_assert(git_error_last() != NULL); cl_assert(git_error_last()->klass == GIT_ERROR_NOMEMORY); str_in_error = strstr(git_error_last()->message, "memory"); cl_assert(str_in_error != NULL); git_error_clear(); git_error_set(GIT_ERROR_REPOSITORY, "This is a test"); /* internal fn */ cl_assert(git_error_last() != NULL); str_in_error = strstr(git_error_last()->message, "This is a test"); cl_assert(str_in_error != NULL); git_error_clear(); cl_assert(git_error_last() == NULL); do { struct stat st; memset(&st, 0, sizeof(st)); cl_assert(p_lstat("this_file_does_not_exist", &st) < 0); GIT_UNUSED(st); } while (false); git_error_set(GIT_ERROR_OS, "stat failed"); /* internal fn */ cl_assert(git_error_last() != NULL); str_in_error = strstr(git_error_last()->message, "stat failed"); cl_assert(str_in_error != NULL); cl_assert(git__prefixcmp(str_in_error, "stat failed: ") == 0); cl_assert(strlen(str_in_error) > strlen("stat failed: ")); #ifdef GIT_WIN32 git_error_clear(); /* The MSDN docs use this to generate a sample error */ cl_assert(GetProcessId(NULL) == 0); git_error_set(GIT_ERROR_OS, "GetProcessId failed"); /* internal fn */ cl_assert(git_error_last() != NULL); str_in_error = strstr(git_error_last()->message, "GetProcessId failed"); cl_assert(str_in_error != NULL); cl_assert(git__prefixcmp(str_in_error, "GetProcessId failed: ") == 0); cl_assert(strlen(str_in_error) > strlen("GetProcessId failed: ")); #endif git_error_clear(); } void test_errors__restore(void) { git_error_state err_state = {0}; git_error_clear(); cl_assert(git_error_last() == NULL); cl_assert_equal_i(0, git_error_state_capture(&err_state, 0)); memset(&err_state, 0x0, sizeof(git_error_state)); git_error_set(42, "Foo: %s", "bar"); cl_assert_equal_i(-1, git_error_state_capture(&err_state, -1)); cl_assert(git_error_last() == NULL); git_error_set(99, "Bar: %s", "foo"); git_error_state_restore(&err_state); cl_assert_equal_i(42, git_error_last()->klass); cl_assert_equal_s("Foo: bar", git_error_last()->message); } void test_errors__free_state(void) { git_error_state err_state = {0}; git_error_clear(); git_error_set(42, "Foo: %s", "bar"); cl_assert_equal_i(-1, git_error_state_capture(&err_state, -1)); git_error_set(99, "Bar: %s", "foo"); git_error_state_free(&err_state); cl_assert_equal_i(99, git_error_last()->klass); cl_assert_equal_s("Bar: foo", git_error_last()->message); git_error_state_restore(&err_state); cl_assert(git_error_last() == NULL); } void test_errors__restore_oom(void) { git_error_state err_state = {0}; const git_error *oom_error = NULL; git_error_clear(); git_error_set_oom(); /* internal fn */ oom_error = git_error_last(); cl_assert(oom_error); cl_assert_equal_i(-1, git_error_state_capture(&err_state, -1)); cl_assert(git_error_last() == NULL); cl_assert_equal_i(GIT_ERROR_NOMEMORY, err_state.error_msg.klass); cl_assert_equal_s("Out of memory", err_state.error_msg.message); git_error_state_restore(&err_state); cl_assert(git_error_last()->klass == GIT_ERROR_NOMEMORY); cl_assert_(git_error_last() == oom_error, "static oom error not restored"); git_error_clear(); } static int test_arraysize_multiply(size_t nelem, size_t size) { size_t out; GIT_ERROR_CHECK_ALLOC_MULTIPLY(&out, nelem, size); return 0; } void test_errors__integer_overflow_alloc_multiply(void) { cl_git_pass(test_arraysize_multiply(10, 10)); cl_git_pass(test_arraysize_multiply(1000, 1000)); cl_git_pass(test_arraysize_multiply(SIZE_MAX/sizeof(void *), sizeof(void *))); cl_git_pass(test_arraysize_multiply(0, 10)); cl_git_pass(test_arraysize_multiply(10, 0)); cl_git_fail(test_arraysize_multiply(SIZE_MAX-1, sizeof(void *))); cl_git_fail(test_arraysize_multiply((SIZE_MAX/sizeof(void *))+1, sizeof(void *))); cl_assert_equal_i(GIT_ERROR_NOMEMORY, git_error_last()->klass); cl_assert_equal_s("Out of memory", git_error_last()->message); } static int test_arraysize_add(size_t one, size_t two) { size_t out; GIT_ERROR_CHECK_ALLOC_ADD(&out, one, two); return 0; } void test_errors__integer_overflow_alloc_add(void) { cl_git_pass(test_arraysize_add(10, 10)); cl_git_pass(test_arraysize_add(1000, 1000)); cl_git_pass(test_arraysize_add(SIZE_MAX-10, 10)); cl_git_fail(test_arraysize_multiply(SIZE_MAX-1, 2)); cl_git_fail(test_arraysize_multiply(SIZE_MAX, SIZE_MAX)); cl_assert_equal_i(GIT_ERROR_NOMEMORY, git_error_last()->klass); cl_assert_equal_s("Out of memory", git_error_last()->message); } void test_errors__integer_overflow_sets_oom(void) { size_t out; git_error_clear(); cl_assert(!GIT_ADD_SIZET_OVERFLOW(&out, SIZE_MAX-1, 1)); cl_assert_equal_p(NULL, git_error_last()); git_error_clear(); cl_assert(!GIT_ADD_SIZET_OVERFLOW(&out, 42, 69)); cl_assert_equal_p(NULL, git_error_last()); git_error_clear(); cl_assert(GIT_ADD_SIZET_OVERFLOW(&out, SIZE_MAX, SIZE_MAX)); cl_assert_equal_i(GIT_ERROR_NOMEMORY, git_error_last()->klass); cl_assert_equal_s("Out of memory", git_error_last()->message); git_error_clear(); cl_assert(GIT_ADD_SIZET_OVERFLOW(&out, SIZE_MAX, SIZE_MAX)); cl_assert_equal_i(GIT_ERROR_NOMEMORY, git_error_last()->klass); cl_assert_equal_s("Out of memory", git_error_last()->message); }
libgit2-main
tests/util/errors.c
#include "clar_libgit2.h" #include "futils.h" typedef struct name_data { int count; /* return count */ char *name; /* filename */ } name_data; typedef struct walk_data { char *sub; /* sub-directory name */ name_data *names; /* name state data */ git_str path; } walk_data; static char *top_dir = "dir-walk"; static walk_data *state_loc; static void setup(walk_data *d) { name_data *n; cl_must_pass(p_mkdir(top_dir, 0777)); cl_must_pass(p_chdir(top_dir)); if (strcmp(d->sub, ".") != 0) cl_must_pass(p_mkdir(d->sub, 0777)); cl_git_pass(git_str_sets(&d->path, d->sub)); state_loc = d; for (n = d->names; n->name; n++) { git_file fd = p_creat(n->name, 0666); cl_assert(fd >= 0); p_close(fd); n->count = 0; } } static void dirent_cleanup__cb(void *_d) { walk_data *d = _d; name_data *n; for (n = d->names; n->name; n++) { cl_must_pass(p_unlink(n->name)); } if (strcmp(d->sub, ".") != 0) cl_must_pass(p_rmdir(d->sub)); cl_must_pass(p_chdir("..")); cl_must_pass(p_rmdir(top_dir)); git_str_dispose(&d->path); } static void check_counts(walk_data *d) { name_data *n; for (n = d->names; n->name; n++) { cl_assert(n->count == 1); } } static int update_count(name_data *data, const char *name) { name_data *n; for (n = data; n->name; n++) { if (!strcmp(n->name, name)) { n->count++; return 0; } } return GIT_ERROR; } static int one_entry(void *state, git_str *path) { walk_data *d = (walk_data *) state; if (state != state_loc) return GIT_ERROR; if (path != &d->path) return GIT_ERROR; return update_count(d->names, path->ptr); } static name_data dot_names[] = { { 0, "./a" }, { 0, "./asdf" }, { 0, "./pack-foo.pack" }, { 0, NULL } }; static walk_data dot = { ".", dot_names, GIT_STR_INIT }; /* make sure that the '.' folder is not traversed */ void test_dirent__dont_traverse_dot(void) { cl_set_cleanup(&dirent_cleanup__cb, &dot); setup(&dot); cl_git_pass(git_fs_path_direach(&dot.path, 0, one_entry, &dot)); check_counts(&dot); } static name_data sub_names[] = { { 0, "sub/a" }, { 0, "sub/asdf" }, { 0, "sub/pack-foo.pack" }, { 0, NULL } }; static walk_data sub = { "sub", sub_names, GIT_STR_INIT }; /* traverse a subfolder */ void test_dirent__traverse_subfolder(void) { cl_set_cleanup(&dirent_cleanup__cb, &sub); setup(&sub); cl_git_pass(git_fs_path_direach(&sub.path, 0, one_entry, &sub)); check_counts(&sub); } static walk_data sub_slash = { "sub/", sub_names, GIT_STR_INIT }; /* traverse a slash-terminated subfolder */ void test_dirent__traverse_slash_terminated_folder(void) { cl_set_cleanup(&dirent_cleanup__cb, &sub_slash); setup(&sub_slash); cl_git_pass(git_fs_path_direach(&sub_slash.path, 0, one_entry, &sub_slash)); check_counts(&sub_slash); } static name_data empty_names[] = { { 0, NULL } }; static walk_data empty = { "empty", empty_names, GIT_STR_INIT }; /* make sure that empty folders are not traversed */ void test_dirent__dont_traverse_empty_folders(void) { cl_set_cleanup(&dirent_cleanup__cb, &empty); setup(&empty); cl_git_pass(git_fs_path_direach(&empty.path, 0, one_entry, &empty)); check_counts(&empty); /* make sure callback not called */ cl_assert(git_fs_path_is_empty_dir(empty.path.ptr)); } static name_data odd_names[] = { { 0, "odd/.a" }, { 0, "odd/..c" }, /* the following don't work on cygwin/win32 */ /* { 0, "odd/.b." }, */ /* { 0, "odd/..d.." }, */ { 0, NULL } }; static walk_data odd = { "odd", odd_names, GIT_STR_INIT }; /* make sure that strange looking filenames ('..c') are traversed */ void test_dirent__traverse_weird_filenames(void) { cl_set_cleanup(&dirent_cleanup__cb, &odd); setup(&odd); cl_git_pass(git_fs_path_direach(&odd.path, 0, one_entry, &odd)); check_counts(&odd); } /* test filename length limits */ void test_dirent__length_limits(void) { char *big_filename = (char *)git__malloc(FILENAME_MAX + 1); memset(big_filename, 'a', FILENAME_MAX + 1); big_filename[FILENAME_MAX] = 0; cl_must_fail(p_creat(big_filename, 0666)); git__free(big_filename); } void test_dirent__empty_dir(void) { cl_must_pass(p_mkdir("empty_dir", 0777)); cl_assert(git_fs_path_is_empty_dir("empty_dir")); cl_git_mkfile("empty_dir/content", "whatever\n"); cl_assert(!git_fs_path_is_empty_dir("empty_dir")); cl_assert(!git_fs_path_is_empty_dir("empty_dir/content")); cl_must_pass(p_unlink("empty_dir/content")); cl_must_pass(p_mkdir("empty_dir/content", 0777)); cl_assert(!git_fs_path_is_empty_dir("empty_dir")); cl_assert(git_fs_path_is_empty_dir("empty_dir/content")); cl_must_pass(p_rmdir("empty_dir/content")); cl_must_pass(p_rmdir("empty_dir")); } static void handle_next(git_fs_path_diriter *diriter, walk_data *walk) { const char *fullpath, *filename; size_t fullpath_len, filename_len; cl_git_pass(git_fs_path_diriter_fullpath(&fullpath, &fullpath_len, diriter)); cl_git_pass(git_fs_path_diriter_filename(&filename, &filename_len, diriter)); cl_assert_equal_strn(fullpath, "sub/", 4); cl_assert_equal_s(fullpath+4, filename); update_count(walk->names, fullpath); } /* test directory iterator */ void test_dirent__diriter_with_fullname(void) { git_fs_path_diriter diriter = GIT_FS_PATH_DIRITER_INIT; int error; cl_set_cleanup(&dirent_cleanup__cb, &sub); setup(&sub); cl_git_pass(git_fs_path_diriter_init(&diriter, sub.path.ptr, 0)); while ((error = git_fs_path_diriter_next(&diriter)) == 0) handle_next(&diriter, &sub); cl_assert_equal_i(error, GIT_ITEROVER); git_fs_path_diriter_free(&diriter); check_counts(&sub); } void test_dirent__diriter_at_directory_root(void) { git_fs_path_diriter diriter = GIT_FS_PATH_DIRITER_INIT; const char *sandbox_path, *path; char *root_path; size_t path_len; int root_offset, error; sandbox_path = clar_sandbox_path(); cl_assert((root_offset = git_fs_path_root(sandbox_path)) >= 0); cl_assert(root_path = git__calloc(1, root_offset + 2)); strncpy(root_path, sandbox_path, root_offset + 1); cl_git_pass(git_fs_path_diriter_init(&diriter, root_path, 0)); while ((error = git_fs_path_diriter_next(&diriter)) == 0) { cl_git_pass(git_fs_path_diriter_fullpath(&path, &path_len, &diriter)); cl_assert(path_len > (size_t)(root_offset + 1)); cl_assert(path[root_offset+1] != '/'); } cl_assert_equal_i(error, GIT_ITEROVER); git_fs_path_diriter_free(&diriter); git__free(root_path); }
libgit2-main
tests/util/dirent.c
#include "clar_libgit2.h" #include "fs_path.h" static void test_make_relative( const char *expected_path, const char *path, const char *parent, int expected_status) { git_str buf = GIT_STR_INIT; git_str_puts(&buf, path); cl_assert_equal_i(expected_status, git_fs_path_make_relative(&buf, parent)); cl_assert_equal_s(expected_path, buf.ptr); git_str_dispose(&buf); } void test_path_core__make_relative(void) { test_make_relative("foo.c", "/path/to/foo.c", "/path/to", 0); test_make_relative("bar/foo.c", "/path/to/bar/foo.c", "/path/to", 0); test_make_relative("foo.c", "/path/to/foo.c", "/path/to/", 0); test_make_relative("", "/path/to", "/path/to", 0); test_make_relative("", "/path/to", "/path/to/", 0); test_make_relative("../", "/path/to", "/path/to/foo", 0); test_make_relative("../foo.c", "/path/to/foo.c", "/path/to/bar", 0); test_make_relative("../bar/foo.c", "/path/to/bar/foo.c", "/path/to/baz", 0); test_make_relative("../../foo.c", "/path/to/foo.c", "/path/to/foo/bar", 0); test_make_relative("../../foo/bar.c", "/path/to/foo/bar.c", "/path/to/bar/foo", 0); test_make_relative("../../foo.c", "/foo.c", "/bar/foo", 0); test_make_relative("foo.c", "/path/to/foo.c", "/path/to/", 0); test_make_relative("../foo.c", "/path/to/foo.c", "/path/to/bar/", 0); test_make_relative("foo.c", "d:/path/to/foo.c", "d:/path/to", 0); test_make_relative("../foo", "/foo", "/bar", 0); test_make_relative("path/to/foo.c", "/path/to/foo.c", "/", 0); test_make_relative("../foo", "path/to/foo", "path/to/bar", 0); test_make_relative("/path/to/foo.c", "/path/to/foo.c", "d:/path/to", GIT_ENOTFOUND); test_make_relative("d:/path/to/foo.c", "d:/path/to/foo.c", "/path/to", GIT_ENOTFOUND); test_make_relative("/path/to/foo.c", "/path/to/foo.c", "not-a-rooted-path", GIT_ENOTFOUND); test_make_relative("not-a-rooted-path", "not-a-rooted-path", "/path/to", GIT_ENOTFOUND); test_make_relative("/path", "/path", "pathtofoo", GIT_ENOTFOUND); test_make_relative("path", "path", "pathtofoo", GIT_ENOTFOUND); } void test_path_core__isvalid_standard(void) { cl_assert_equal_b(true, git_fs_path_is_valid("foo/bar", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo/bar/file.txt", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo/bar/.file", 0)); } /* Ensure that `is_valid_str` only reads str->size bytes */ void test_path_core__isvalid_standard_str(void) { git_str str = GIT_STR_INIT_CONST("foo/bar//zap", 0); unsigned int flags = GIT_FS_PATH_REJECT_EMPTY_COMPONENT; str.size = 0; cl_assert_equal_b(false, git_fs_path_str_is_valid(&str, flags)); str.size = 3; cl_assert_equal_b(true, git_fs_path_str_is_valid(&str, flags)); str.size = 4; cl_assert_equal_b(false, git_fs_path_str_is_valid(&str, flags)); str.size = 5; cl_assert_equal_b(true, git_fs_path_str_is_valid(&str, flags)); str.size = 7; cl_assert_equal_b(true, git_fs_path_str_is_valid(&str, flags)); str.size = 8; cl_assert_equal_b(false, git_fs_path_str_is_valid(&str, flags)); str.size = strlen(str.ptr); cl_assert_equal_b(false, git_fs_path_str_is_valid(&str, flags)); } void test_path_core__isvalid_empty_dir_component(void) { unsigned int flags = GIT_FS_PATH_REJECT_EMPTY_COMPONENT; /* empty component */ cl_assert_equal_b(true, git_fs_path_is_valid("foo//bar", 0)); /* leading slash */ cl_assert_equal_b(true, git_fs_path_is_valid("/", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("/foo", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("/foo/bar", 0)); /* trailing slash */ cl_assert_equal_b(true, git_fs_path_is_valid("foo/", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo/bar/", 0)); /* empty component */ cl_assert_equal_b(false, git_fs_path_is_valid("foo//bar", flags)); /* leading slash */ cl_assert_equal_b(false, git_fs_path_is_valid("/", flags)); cl_assert_equal_b(false, git_fs_path_is_valid("/foo", flags)); cl_assert_equal_b(false, git_fs_path_is_valid("/foo/bar", flags)); /* trailing slash */ cl_assert_equal_b(false, git_fs_path_is_valid("foo/", flags)); cl_assert_equal_b(false, git_fs_path_is_valid("foo/bar/", flags)); } void test_path_core__isvalid_dot_and_dotdot(void) { cl_assert_equal_b(true, git_fs_path_is_valid(".", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("./foo", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo/.", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("./foo", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("..", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("../foo", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo/..", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("../foo", 0)); cl_assert_equal_b(false, git_fs_path_is_valid(".", GIT_FS_PATH_REJECT_TRAVERSAL)); cl_assert_equal_b(false, git_fs_path_is_valid("./foo", GIT_FS_PATH_REJECT_TRAVERSAL)); cl_assert_equal_b(false, git_fs_path_is_valid("foo/.", GIT_FS_PATH_REJECT_TRAVERSAL)); cl_assert_equal_b(false, git_fs_path_is_valid("./foo", GIT_FS_PATH_REJECT_TRAVERSAL)); cl_assert_equal_b(false, git_fs_path_is_valid("..", GIT_FS_PATH_REJECT_TRAVERSAL)); cl_assert_equal_b(false, git_fs_path_is_valid("../foo", GIT_FS_PATH_REJECT_TRAVERSAL)); cl_assert_equal_b(false, git_fs_path_is_valid("foo/..", GIT_FS_PATH_REJECT_TRAVERSAL)); cl_assert_equal_b(false, git_fs_path_is_valid("../foo", GIT_FS_PATH_REJECT_TRAVERSAL)); } void test_path_core__isvalid_backslash(void) { cl_assert_equal_b(true, git_fs_path_is_valid("foo\\file.txt", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo/bar\\file.txt", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo/bar\\", 0)); cl_assert_equal_b(false, git_fs_path_is_valid("foo\\file.txt", GIT_FS_PATH_REJECT_BACKSLASH)); cl_assert_equal_b(false, git_fs_path_is_valid("foo/bar\\file.txt", GIT_FS_PATH_REJECT_BACKSLASH)); cl_assert_equal_b(false, git_fs_path_is_valid("foo/bar\\", GIT_FS_PATH_REJECT_BACKSLASH)); } void test_path_core__isvalid_trailing_dot(void) { cl_assert_equal_b(true, git_fs_path_is_valid("foo.", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo...", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo/bar.", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo./bar", 0)); cl_assert_equal_b(false, git_fs_path_is_valid("foo.", GIT_FS_PATH_REJECT_TRAILING_DOT)); cl_assert_equal_b(false, git_fs_path_is_valid("foo...", GIT_FS_PATH_REJECT_TRAILING_DOT)); cl_assert_equal_b(false, git_fs_path_is_valid("foo/bar.", GIT_FS_PATH_REJECT_TRAILING_DOT)); cl_assert_equal_b(false, git_fs_path_is_valid("foo./bar", GIT_FS_PATH_REJECT_TRAILING_DOT)); } void test_path_core__isvalid_trailing_space(void) { cl_assert_equal_b(true, git_fs_path_is_valid("foo ", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo ", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo/bar ", 0)); cl_assert_equal_b(true, git_fs_path_is_valid(" ", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo /bar", 0)); cl_assert_equal_b(false, git_fs_path_is_valid("foo ", GIT_FS_PATH_REJECT_TRAILING_SPACE)); cl_assert_equal_b(false, git_fs_path_is_valid("foo ", GIT_FS_PATH_REJECT_TRAILING_SPACE)); cl_assert_equal_b(false, git_fs_path_is_valid("foo/bar ", GIT_FS_PATH_REJECT_TRAILING_SPACE)); cl_assert_equal_b(false, git_fs_path_is_valid(" ", GIT_FS_PATH_REJECT_TRAILING_SPACE)); cl_assert_equal_b(false, git_fs_path_is_valid("foo /bar", GIT_FS_PATH_REJECT_TRAILING_SPACE)); } void test_path_core__isvalid_trailing_colon(void) { cl_assert_equal_b(true, git_fs_path_is_valid("foo:", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo/bar:", 0)); cl_assert_equal_b(true, git_fs_path_is_valid(":", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("foo:/bar", 0)); cl_assert_equal_b(false, git_fs_path_is_valid("foo:", GIT_FS_PATH_REJECT_TRAILING_COLON)); cl_assert_equal_b(false, git_fs_path_is_valid("foo/bar:", GIT_FS_PATH_REJECT_TRAILING_COLON)); cl_assert_equal_b(false, git_fs_path_is_valid(":", GIT_FS_PATH_REJECT_TRAILING_COLON)); cl_assert_equal_b(false, git_fs_path_is_valid("foo:/bar", GIT_FS_PATH_REJECT_TRAILING_COLON)); } void test_path_core__isvalid_dos_paths(void) { cl_assert_equal_b(true, git_fs_path_is_valid("aux", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("aux.", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("aux:", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("aux.asdf", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("aux.asdf\\zippy", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("aux:asdf\\foobar", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("con", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("prn", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("nul", 0)); cl_assert_equal_b(false, git_fs_path_is_valid("aux", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("aux.", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("aux:", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("aux.asdf", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("aux.asdf\\zippy", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("aux:asdf\\foobar", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("con", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("prn", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("nul", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(true, git_fs_path_is_valid("aux1", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("aux1", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(true, git_fs_path_is_valid("auxn", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(true, git_fs_path_is_valid("aux\\foo", GIT_FS_PATH_REJECT_DOS_PATHS)); } void test_path_core__isvalid_dos_paths_withnum(void) { cl_assert_equal_b(true, git_fs_path_is_valid("com1", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("com1.", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("com1:", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("com1.asdf", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("com1.asdf\\zippy", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("com1:asdf\\foobar", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("com1\\foo", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("lpt1", 0)); cl_assert_equal_b(false, git_fs_path_is_valid("com1", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("com1.", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("com1:", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("com1.asdf", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("com1.asdf\\zippy", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("com1:asdf\\foobar", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("com1/foo", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(false, git_fs_path_is_valid("lpt1", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(true, git_fs_path_is_valid("com0", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("com0", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(true, git_fs_path_is_valid("com10", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("com10", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(true, git_fs_path_is_valid("comn", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(true, git_fs_path_is_valid("com1\\foo", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(true, git_fs_path_is_valid("lpt0", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(true, git_fs_path_is_valid("lpt10", GIT_FS_PATH_REJECT_DOS_PATHS)); cl_assert_equal_b(true, git_fs_path_is_valid("lptn", GIT_FS_PATH_REJECT_DOS_PATHS)); } void test_path_core__isvalid_nt_chars(void) { cl_assert_equal_b(true, git_fs_path_is_valid("asdf\001foo", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("asdf\037bar", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("asdf<bar", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("asdf>foo", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("asdf:foo", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("asdf\"bar", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("asdf|foo", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("asdf?bar", 0)); cl_assert_equal_b(true, git_fs_path_is_valid("asdf*bar", 0)); cl_assert_equal_b(false, git_fs_path_is_valid("asdf\001foo", GIT_FS_PATH_REJECT_NT_CHARS)); cl_assert_equal_b(false, git_fs_path_is_valid("asdf\037bar", GIT_FS_PATH_REJECT_NT_CHARS)); cl_assert_equal_b(false, git_fs_path_is_valid("asdf<bar", GIT_FS_PATH_REJECT_NT_CHARS)); cl_assert_equal_b(false, git_fs_path_is_valid("asdf>foo", GIT_FS_PATH_REJECT_NT_CHARS)); cl_assert_equal_b(false, git_fs_path_is_valid("asdf:foo", GIT_FS_PATH_REJECT_NT_CHARS)); cl_assert_equal_b(false, git_fs_path_is_valid("asdf\"bar", GIT_FS_PATH_REJECT_NT_CHARS)); cl_assert_equal_b(false, git_fs_path_is_valid("asdf|foo", GIT_FS_PATH_REJECT_NT_CHARS)); cl_assert_equal_b(false, git_fs_path_is_valid("asdf?bar", GIT_FS_PATH_REJECT_NT_CHARS)); cl_assert_equal_b(false, git_fs_path_is_valid("asdf*bar", GIT_FS_PATH_REJECT_NT_CHARS)); } static void test_join_unrooted( const char *expected_result, ssize_t expected_rootlen, const char *path, const char *base) { git_str result = GIT_STR_INIT; ssize_t root_at; cl_git_pass(git_fs_path_join_unrooted(&result, path, base, &root_at)); cl_assert_equal_s(expected_result, result.ptr); cl_assert_equal_i(expected_rootlen, root_at); git_str_dispose(&result); } void test_path_core__join_unrooted(void) { git_str out = GIT_STR_INIT; test_join_unrooted("foo", 0, "foo", NULL); test_join_unrooted("foo/bar", 0, "foo/bar", NULL); /* Relative paths have base prepended */ test_join_unrooted("/foo/bar", 4, "bar", "/foo"); test_join_unrooted("/foo/bar/foobar", 4, "bar/foobar", "/foo"); test_join_unrooted("c:/foo/bar/foobar", 6, "bar/foobar", "c:/foo"); test_join_unrooted("c:/foo/bar/foobar", 10, "foobar", "c:/foo/bar"); /* Absolute paths are not prepended with base */ test_join_unrooted("/foo", 0, "/foo", "/asdf"); test_join_unrooted("/foo/bar", 0, "/foo/bar", "/asdf"); /* Drive letter is given as root length on Windows */ test_join_unrooted("c:/foo", 2, "c:/foo", "c:/asdf"); test_join_unrooted("c:/foo/bar", 2, "c:/foo/bar", "c:/asdf"); #ifdef GIT_WIN32 /* Paths starting with '\\' are absolute */ test_join_unrooted("\\bar", 0, "\\bar", "c:/foo/"); test_join_unrooted("\\\\network\\bar", 9, "\\\\network\\bar", "c:/foo/"); #else /* Paths starting with '\\' are not absolute on non-Windows systems */ test_join_unrooted("/foo/\\bar", 4, "\\bar", "/foo"); test_join_unrooted("c:/foo/\\bar", 7, "\\bar", "c:/foo/"); #endif /* Base is returned when it's provided and is the prefix */ test_join_unrooted("c:/foo/bar/foobar", 6, "c:/foo/bar/foobar", "c:/foo"); test_join_unrooted("c:/foo/bar/foobar", 10, "c:/foo/bar/foobar", "c:/foo/bar"); /* Trailing slash in the base is ignored */ test_join_unrooted("c:/foo/bar/foobar", 6, "c:/foo/bar/foobar", "c:/foo/"); git_str_dispose(&out); } void test_path_core__join_unrooted_respects_funny_windows_roots(void) { test_join_unrooted("💩:/foo/bar/foobar", 9, "bar/foobar", "💩:/foo"); test_join_unrooted("💩:/foo/bar/foobar", 13, "foobar", "💩:/foo/bar"); test_join_unrooted("💩:/foo", 5, "💩:/foo", "💩:/asdf"); test_join_unrooted("💩:/foo/bar", 5, "💩:/foo/bar", "💩:/asdf"); test_join_unrooted("💩:/foo/bar/foobar", 9, "💩:/foo/bar/foobar", "💩:/foo"); test_join_unrooted("💩:/foo/bar/foobar", 13, "💩:/foo/bar/foobar", "💩:/foo/bar"); test_join_unrooted("💩:/foo/bar/foobar", 9, "💩:/foo/bar/foobar", "💩:/foo/"); }
libgit2-main
tests/util/path/core.c
#include "clar_libgit2.h" #ifdef GIT_WIN32 #include "win32/path_w32.h" #endif #ifdef GIT_WIN32 static void test_utf8_to_utf16(const char *utf8_in, const wchar_t *utf16_expected) { git_win32_path path_utf16; int path_utf16len; cl_assert((path_utf16len = git_win32_path_from_utf8(path_utf16, utf8_in)) >= 0); cl_assert_equal_wcs(utf16_expected, path_utf16); cl_assert_equal_i(wcslen(utf16_expected), path_utf16len); } static void test_utf8_to_utf16_relative(const char* utf8_in, const wchar_t* utf16_expected) { git_win32_path path_utf16; int path_utf16len; cl_assert((path_utf16len = git_win32_path_relative_from_utf8(path_utf16, utf8_in)) >= 0); cl_assert_equal_wcs(utf16_expected, path_utf16); cl_assert_equal_i(wcslen(utf16_expected), path_utf16len); } #endif void test_path_win32__utf8_to_utf16(void) { #ifdef GIT_WIN32 test_utf8_to_utf16("C:\\", L"\\\\?\\C:\\"); test_utf8_to_utf16("c:\\", L"\\\\?\\c:\\"); test_utf8_to_utf16("C:/", L"\\\\?\\C:\\"); test_utf8_to_utf16("c:/", L"\\\\?\\c:\\"); #endif } void test_path_win32__removes_trailing_slash(void) { #ifdef GIT_WIN32 test_utf8_to_utf16("C:\\Foo\\", L"\\\\?\\C:\\Foo"); test_utf8_to_utf16("C:\\Foo\\\\", L"\\\\?\\C:\\Foo"); test_utf8_to_utf16("C:\\Foo\\\\", L"\\\\?\\C:\\Foo"); test_utf8_to_utf16("C:/Foo/", L"\\\\?\\C:\\Foo"); test_utf8_to_utf16("C:/Foo///", L"\\\\?\\C:\\Foo"); #endif } void test_path_win32__squashes_multiple_slashes(void) { #ifdef GIT_WIN32 test_utf8_to_utf16("C:\\\\Foo\\Bar\\\\Foobar", L"\\\\?\\C:\\Foo\\Bar\\Foobar"); test_utf8_to_utf16("C://Foo/Bar///Foobar", L"\\\\?\\C:\\Foo\\Bar\\Foobar"); #endif } void test_path_win32__unc(void) { #ifdef GIT_WIN32 test_utf8_to_utf16("\\\\server\\c$\\unc\\path", L"\\\\?\\UNC\\server\\c$\\unc\\path"); test_utf8_to_utf16("//server/git/style/unc/path", L"\\\\?\\UNC\\server\\git\\style\\unc\\path"); #endif } void test_path_win32__honors_max_path(void) { #ifdef GIT_WIN32 git_win32_path path_utf16; test_utf8_to_utf16("C:\\This path is 261 characters which is fine for our path handling functions which cope with paths longer than MAX_PATH\\0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghijk", L"\\\\?\\C:\\This path is 261 characters which is fine for our path handling functions which cope with paths longer than MAX_PATH\\0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghijk"); cl_check_fail(git_win32_path_from_utf8(path_utf16, "C:\\This path is 4097 chars and exceeds our maximum path length on Windows which is limited to 4096 characters\\alas\\0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij0123456789abcdefghij01")); #endif } void test_path_win32__dot_and_dotdot(void) { #ifdef GIT_WIN32 test_utf8_to_utf16("C:\\Foo\\..\\Foobar", L"\\\\?\\C:\\Foobar"); test_utf8_to_utf16("C:\\Foo\\Bar\\..\\Foobar", L"\\\\?\\C:\\Foo\\Foobar"); test_utf8_to_utf16("C:\\Foo\\Bar\\..\\Foobar\\..", L"\\\\?\\C:\\Foo"); test_utf8_to_utf16("C:\\Foobar\\..", L"\\\\?\\C:\\"); test_utf8_to_utf16("C:/Foo/Bar/../Foobar", L"\\\\?\\C:\\Foo\\Foobar"); test_utf8_to_utf16("C:/Foo/Bar/../Foobar/../Asdf/", L"\\\\?\\C:\\Foo\\Asdf"); test_utf8_to_utf16("C:/Foo/Bar/../Foobar/..", L"\\\\?\\C:\\Foo"); test_utf8_to_utf16("C:/Foo/..", L"\\\\?\\C:\\"); test_utf8_to_utf16("C:\\Foo\\Bar\\.\\Foobar", L"\\\\?\\C:\\Foo\\Bar\\Foobar"); test_utf8_to_utf16("C:\\.\\Foo\\.\\Bar\\.\\Foobar\\.\\", L"\\\\?\\C:\\Foo\\Bar\\Foobar"); test_utf8_to_utf16("C:/Foo/Bar/./Foobar", L"\\\\?\\C:\\Foo\\Bar\\Foobar"); test_utf8_to_utf16("C:/Foo/../Bar/./Foobar/../", L"\\\\?\\C:\\Bar"); test_utf8_to_utf16("C:\\Foo\\..\\..\\Bar", L"\\\\?\\C:\\Bar"); #endif } void test_path_win32__absolute_from_no_drive_letter(void) { #ifdef GIT_WIN32 test_utf8_to_utf16("\\Foo", L"\\\\?\\C:\\Foo"); test_utf8_to_utf16("\\Foo\\Bar", L"\\\\?\\C:\\Foo\\Bar"); test_utf8_to_utf16("/Foo/Bar", L"\\\\?\\C:\\Foo\\Bar"); #endif } void test_path_win32__absolute_from_relative(void) { #ifdef GIT_WIN32 char cwd_backup[MAX_PATH]; cl_must_pass(p_getcwd(cwd_backup, MAX_PATH)); cl_must_pass(p_chdir("C:/")); test_utf8_to_utf16("Foo", L"\\\\?\\C:\\Foo"); test_utf8_to_utf16("..\\..\\Foo", L"\\\\?\\C:\\Foo"); test_utf8_to_utf16("Foo\\..", L"\\\\?\\C:\\"); test_utf8_to_utf16("Foo\\..\\..", L"\\\\?\\C:\\"); test_utf8_to_utf16("", L"\\\\?\\C:\\"); cl_must_pass(p_chdir("C:/Windows")); test_utf8_to_utf16("Foo", L"\\\\?\\C:\\Windows\\Foo"); test_utf8_to_utf16("Foo\\Bar", L"\\\\?\\C:\\Windows\\Foo\\Bar"); test_utf8_to_utf16("..\\Foo", L"\\\\?\\C:\\Foo"); test_utf8_to_utf16("Foo\\..\\Bar", L"\\\\?\\C:\\Windows\\Bar"); test_utf8_to_utf16("", L"\\\\?\\C:\\Windows"); cl_must_pass(p_chdir(cwd_backup)); #endif } void test_path_win32__keeps_relative(void) { #ifdef GIT_WIN32 /* Relative paths stay relative */ test_utf8_to_utf16_relative("Foo", L"Foo"); test_utf8_to_utf16_relative("..\\..\\Foo", L"..\\..\\Foo"); test_utf8_to_utf16_relative("Foo\\..", L"Foo\\.."); test_utf8_to_utf16_relative("Foo\\..\\..", L"Foo\\..\\.."); test_utf8_to_utf16_relative("Foo\\Bar", L"Foo\\Bar"); test_utf8_to_utf16_relative("Foo\\..\\Bar", L"Foo\\..\\Bar"); test_utf8_to_utf16_relative("../../Foo", L"..\\..\\Foo"); test_utf8_to_utf16_relative("Foo/..", L"Foo\\.."); test_utf8_to_utf16_relative("Foo/../..", L"Foo\\..\\.."); test_utf8_to_utf16_relative("Foo/Bar", L"Foo\\Bar"); test_utf8_to_utf16_relative("Foo/../Bar", L"Foo\\..\\Bar"); test_utf8_to_utf16_relative("Foo/../Bar/", L"Foo\\..\\Bar\\"); test_utf8_to_utf16_relative("", L""); /* Absolute paths are canonicalized */ test_utf8_to_utf16_relative("\\Foo", L"\\\\?\\C:\\Foo"); test_utf8_to_utf16_relative("/Foo/Bar/", L"\\\\?\\C:\\Foo\\Bar"); test_utf8_to_utf16_relative("\\\\server\\c$\\unc\\path", L"\\\\?\\UNC\\server\\c$\\unc\\path"); #endif } #ifdef GIT_WIN32 static void test_canonicalize(const wchar_t *in, const wchar_t *expected) { git_win32_path canonical; cl_assert(wcslen(in) < MAX_PATH); wcscpy(canonical, in); cl_must_pass(git_win32_path_canonicalize(canonical)); cl_assert_equal_wcs(expected, canonical); } #endif static void test_remove_namespace(const wchar_t *in, const wchar_t *expected) { #ifdef GIT_WIN32 git_win32_path canonical; cl_assert(wcslen(in) < MAX_PATH); wcscpy(canonical, in); git_win32_path_remove_namespace(canonical, wcslen(in)); cl_assert_equal_wcs(expected, canonical); #else GIT_UNUSED(in); GIT_UNUSED(expected); #endif } void test_path_win32__remove_namespace(void) { test_remove_namespace(L"\\\\?\\C:\\Temp\\Foo", L"C:\\Temp\\Foo"); test_remove_namespace(L"\\\\?\\C:\\", L"C:\\"); test_remove_namespace(L"\\\\?\\", L""); test_remove_namespace(L"\\??\\C:\\Temp\\Foo", L"C:\\Temp\\Foo"); test_remove_namespace(L"\\??\\C:\\", L"C:\\"); test_remove_namespace(L"\\??\\", L""); test_remove_namespace(L"\\\\?\\UNC\\server\\C$\\folder", L"\\\\server\\C$\\folder"); test_remove_namespace(L"\\\\?\\UNC\\server\\C$\\folder", L"\\\\server\\C$\\folder"); test_remove_namespace(L"\\\\?\\UNC\\server\\C$", L"\\\\server\\C$"); test_remove_namespace(L"\\\\?\\UNC\\server\\", L"\\\\server"); test_remove_namespace(L"\\\\?\\UNC\\server", L"\\\\server"); test_remove_namespace(L"\\??\\UNC\\server\\C$\\folder", L"\\\\server\\C$\\folder"); test_remove_namespace(L"\\??\\UNC\\server\\C$\\folder", L"\\\\server\\C$\\folder"); test_remove_namespace(L"\\??\\UNC\\server\\C$", L"\\\\server\\C$"); test_remove_namespace(L"\\??\\UNC\\server\\", L"\\\\server"); test_remove_namespace(L"\\??\\UNC\\server", L"\\\\server"); test_remove_namespace(L"\\\\server\\C$\\folder", L"\\\\server\\C$\\folder"); test_remove_namespace(L"\\\\server\\C$", L"\\\\server\\C$"); test_remove_namespace(L"\\\\server\\", L"\\\\server"); test_remove_namespace(L"\\\\server", L"\\\\server"); test_remove_namespace(L"C:\\Foo\\Bar", L"C:\\Foo\\Bar"); test_remove_namespace(L"C:\\", L"C:\\"); test_remove_namespace(L"", L""); } void test_path_win32__canonicalize(void) { #ifdef GIT_WIN32 test_canonicalize(L"C:\\Foo\\Bar", L"C:\\Foo\\Bar"); test_canonicalize(L"C:\\Foo\\", L"C:\\Foo"); test_canonicalize(L"C:\\Foo\\\\", L"C:\\Foo"); test_canonicalize(L"C:\\Foo\\..\\Bar", L"C:\\Bar"); test_canonicalize(L"C:\\Foo\\..\\..\\Bar", L"C:\\Bar"); test_canonicalize(L"C:\\Foo\\..\\..\\..\\..\\", L"C:\\"); test_canonicalize(L"C:/Foo/Bar", L"C:\\Foo\\Bar"); test_canonicalize(L"C:/", L"C:\\"); test_canonicalize(L"\\\\?\\C:\\Foo\\Bar", L"\\\\?\\C:\\Foo\\Bar"); test_canonicalize(L"\\\\?\\C:\\Foo\\Bar\\", L"\\\\?\\C:\\Foo\\Bar"); test_canonicalize(L"\\\\?\\C:\\\\Foo\\.\\Bar\\\\..\\", L"\\\\?\\C:\\Foo"); test_canonicalize(L"\\\\?\\C:\\\\", L"\\\\?\\C:\\"); test_canonicalize(L"//?/C:/", L"\\\\?\\C:\\"); test_canonicalize(L"//?/C:/../../Foo/", L"\\\\?\\C:\\Foo"); test_canonicalize(L"//?/C:/Foo/../../", L"\\\\?\\C:\\"); test_canonicalize(L"\\\\?\\UNC\\server\\C$\\folder", L"\\\\?\\UNC\\server\\C$\\folder"); test_canonicalize(L"\\\\?\\UNC\\server\\C$\\folder\\", L"\\\\?\\UNC\\server\\C$\\folder"); test_canonicalize(L"\\\\?\\UNC\\server\\C$\\folder\\", L"\\\\?\\UNC\\server\\C$\\folder"); test_canonicalize(L"\\\\?\\UNC\\server\\C$\\folder\\..\\..\\..\\..\\share\\", L"\\\\?\\UNC\\server\\share"); test_canonicalize(L"\\\\server\\share", L"\\\\server\\share"); test_canonicalize(L"\\\\server\\share\\", L"\\\\server\\share"); test_canonicalize(L"\\\\server\\share\\\\foo\\\\bar", L"\\\\server\\share\\foo\\bar"); test_canonicalize(L"\\\\server\\\\share\\\\foo\\\\bar", L"\\\\server\\share\\foo\\bar"); test_canonicalize(L"\\\\server\\share\\..\\foo", L"\\\\server\\foo"); test_canonicalize(L"\\\\server\\..\\..\\share\\.\\foo", L"\\\\server\\share\\foo"); #endif } void test_path_win32__8dot3_name(void) { #ifdef GIT_WIN32 char *shortname; if (!cl_sandbox_supports_8dot3()) clar__skip(); /* Some guaranteed short names */ cl_assert_equal_s("PROGRA~1", (shortname = git_win32_path_8dot3_name("C:\\Program Files"))); git__free(shortname); cl_assert_equal_s("WINDOWS", (shortname = git_win32_path_8dot3_name("C:\\WINDOWS"))); git__free(shortname); /* Create some predictable short names */ cl_must_pass(p_mkdir(".foo", 0777)); cl_assert_equal_s("FOO~1", (shortname = git_win32_path_8dot3_name(".foo"))); git__free(shortname); cl_git_write2file("bar~1", "foobar\n", 7, O_RDWR|O_CREAT, 0666); cl_must_pass(p_mkdir(".bar", 0777)); cl_assert_equal_s("BAR~2", (shortname = git_win32_path_8dot3_name(".bar"))); git__free(shortname); #endif }
libgit2-main
tests/util/path/win32.c
#include "clar_libgit2.h" /* Override default allocators with ones that will fail predictably. */ static git_allocator std_alloc; static git_allocator oom_alloc; static void *oom_malloc(size_t n, const char *file, int line) { /* Reject any allocation of more than 100 bytes */ return (n > 100) ? NULL : std_alloc.gmalloc(n, file, line); } static void *oom_realloc(void *p, size_t n, const char *file, int line) { /* Reject any allocation of more than 100 bytes */ return (n > 100) ? NULL : std_alloc.grealloc(p, n, file, line); } void test_str_oom__initialize(void) { git_stdalloc_init_allocator(&std_alloc); git_stdalloc_init_allocator(&oom_alloc); oom_alloc.gmalloc = oom_malloc; oom_alloc.grealloc = oom_realloc; cl_git_pass(git_allocator_setup(&oom_alloc)); } void test_str_oom__cleanup(void) { cl_git_pass(git_allocator_setup(NULL)); } void test_str_oom__grow(void) { git_str buf = GIT_STR_INIT; cl_git_pass(git_str_grow(&buf, 42)); cl_assert(!git_str_oom(&buf)); cl_assert(git_str_grow(&buf, 101) == -1); cl_assert(git_str_oom(&buf)); git_str_dispose(&buf); } void test_str_oom__grow_by(void) { git_str buf = GIT_STR_INIT; cl_git_pass(git_str_grow_by(&buf, 42)); cl_assert(!git_str_oom(&buf)); cl_assert(git_str_grow_by(&buf, 101) == -1); cl_assert(git_str_oom(&buf)); }
libgit2-main
tests/util/str/oom.c
#include "clar_libgit2.h" static git_str _buf; void test_str_splice__initialize(void) { git_str_init(&_buf, 16); } void test_str_splice__cleanup(void) { git_str_dispose(&_buf); } void test_str_splice__preprend(void) { git_str_sets(&_buf, "world!"); cl_git_pass(git_str_splice(&_buf, 0, 0, "Hello Dolly", strlen("Hello "))); cl_assert_equal_s("Hello world!", git_str_cstr(&_buf)); } void test_str_splice__append(void) { git_str_sets(&_buf, "Hello"); cl_git_pass(git_str_splice(&_buf, git_str_len(&_buf), 0, " world!", strlen(" world!"))); cl_assert_equal_s("Hello world!", git_str_cstr(&_buf)); } void test_str_splice__insert_at(void) { git_str_sets(&_buf, "Hell world!"); cl_git_pass(git_str_splice(&_buf, strlen("Hell"), 0, "o", strlen("o"))); cl_assert_equal_s("Hello world!", git_str_cstr(&_buf)); } void test_str_splice__remove_at(void) { git_str_sets(&_buf, "Hello world of warcraft!"); cl_git_pass(git_str_splice(&_buf, strlen("Hello world"), strlen(" of warcraft"), "", 0)); cl_assert_equal_s("Hello world!", git_str_cstr(&_buf)); } void test_str_splice__replace(void) { git_str_sets(&_buf, "Hell0 w0rld!"); cl_git_pass(git_str_splice(&_buf, strlen("Hell"), strlen("0 w0"), "o wo", strlen("o wo"))); cl_assert_equal_s("Hello world!", git_str_cstr(&_buf)); } void test_str_splice__replace_with_longer(void) { git_str_sets(&_buf, "Hello you!"); cl_git_pass(git_str_splice(&_buf, strlen("Hello "), strlen("you"), "world", strlen("world"))); cl_assert_equal_s("Hello world!", git_str_cstr(&_buf)); } void test_str_splice__replace_with_shorter(void) { git_str_sets(&_buf, "Brave new world!"); cl_git_pass(git_str_splice(&_buf, 0, strlen("Brave new"), "Hello", strlen("Hello"))); cl_assert_equal_s("Hello world!", git_str_cstr(&_buf)); } void test_str_splice__truncate(void) { git_str_sets(&_buf, "Hello world!!"); cl_git_pass(git_str_splice(&_buf, strlen("Hello world!"), strlen("!"), "", 0)); cl_assert_equal_s("Hello world!", git_str_cstr(&_buf)); } void test_str_splice__dont_do_anything(void) { git_str_sets(&_buf, "Hello world!"); cl_git_pass(git_str_splice(&_buf, 3, 0, "Hello", 0)); cl_assert_equal_s("Hello world!", git_str_cstr(&_buf)); }
libgit2-main
tests/util/str/splice.c
#include "clar_libgit2.h" static const char *test_string = "Have you seen that? Have you seeeen that??"; void test_str_basic__resize(void) { git_str buf1 = GIT_STR_INIT; git_str_puts(&buf1, test_string); cl_assert(git_str_oom(&buf1) == 0); cl_assert_equal_s(git_str_cstr(&buf1), test_string); git_str_puts(&buf1, test_string); cl_assert(strlen(git_str_cstr(&buf1)) == strlen(test_string) * 2); git_str_dispose(&buf1); } void test_str_basic__resize_incremental(void) { git_str buf1 = GIT_STR_INIT; /* Presently, asking for 6 bytes will round up to 8. */ cl_git_pass(git_str_puts(&buf1, "Hello")); cl_assert_equal_i(5, buf1.size); cl_assert_equal_i(8, buf1.asize); /* Ensure an additional byte does not realloc. */ cl_git_pass(git_str_grow_by(&buf1, 1)); cl_assert_equal_i(5, buf1.size); cl_assert_equal_i(8, buf1.asize); /* But requesting many does. */ cl_git_pass(git_str_grow_by(&buf1, 16)); cl_assert_equal_i(5, buf1.size); cl_assert(buf1.asize > 8); git_str_dispose(&buf1); } void test_str_basic__printf(void) { git_str buf2 = GIT_STR_INIT; git_str_printf(&buf2, "%s %s %d ", "shoop", "da", 23); cl_assert(git_str_oom(&buf2) == 0); cl_assert_equal_s(git_str_cstr(&buf2), "shoop da 23 "); git_str_printf(&buf2, "%s %d", "woop", 42); cl_assert(git_str_oom(&buf2) == 0); cl_assert_equal_s(git_str_cstr(&buf2), "shoop da 23 woop 42"); git_str_dispose(&buf2); }
libgit2-main
tests/util/str/basic.c
#include "clar_libgit2.h" static void expect_quote_pass(const char *expected, const char *str) { git_str buf = GIT_STR_INIT; cl_git_pass(git_str_puts(&buf, str)); cl_git_pass(git_str_quote(&buf)); cl_assert_equal_s(expected, git_str_cstr(&buf)); cl_assert_equal_i(strlen(expected), git_str_len(&buf)); git_str_dispose(&buf); } void test_str_quote__quote_succeeds(void) { expect_quote_pass("", ""); expect_quote_pass("foo", "foo"); expect_quote_pass("foo/bar/baz.c", "foo/bar/baz.c"); expect_quote_pass("foo bar", "foo bar"); expect_quote_pass("\"\\\"leading quote\"", "\"leading quote"); expect_quote_pass("\"slash\\\\y\"", "slash\\y"); expect_quote_pass("\"foo\\r\\nbar\"", "foo\r\nbar"); expect_quote_pass("\"foo\\177bar\"", "foo\177bar"); expect_quote_pass("\"foo\\001bar\"", "foo\001bar"); expect_quote_pass("\"foo\\377bar\"", "foo\377bar"); } static void expect_unquote_pass(const char *expected, const char *quoted) { git_str buf = GIT_STR_INIT; cl_git_pass(git_str_puts(&buf, quoted)); cl_git_pass(git_str_unquote(&buf)); cl_assert_equal_s(expected, git_str_cstr(&buf)); cl_assert_equal_i(strlen(expected), git_str_len(&buf)); git_str_dispose(&buf); } static void expect_unquote_fail(const char *quoted) { git_str buf = GIT_STR_INIT; cl_git_pass(git_str_puts(&buf, quoted)); cl_git_fail(git_str_unquote(&buf)); git_str_dispose(&buf); } void test_str_quote__unquote_succeeds(void) { expect_unquote_pass("", "\"\""); expect_unquote_pass(" ", "\" \""); expect_unquote_pass("foo", "\"foo\""); expect_unquote_pass("foo bar", "\"foo bar\""); expect_unquote_pass("foo\"bar", "\"foo\\\"bar\""); expect_unquote_pass("foo\\bar", "\"foo\\\\bar\""); expect_unquote_pass("foo\tbar", "\"foo\\tbar\""); expect_unquote_pass("\vfoo\tbar\n", "\"\\vfoo\\tbar\\n\""); expect_unquote_pass("foo\nbar", "\"foo\\012bar\""); expect_unquote_pass("foo\r\nbar", "\"foo\\015\\012bar\""); expect_unquote_pass("foo\r\nbar", "\"\\146\\157\\157\\015\\012\\142\\141\\162\""); expect_unquote_pass("newline: \n", "\"newline: \\012\""); expect_unquote_pass("0xff: \377", "\"0xff: \\377\""); } void test_str_quote__unquote_fails(void) { expect_unquote_fail("no quotes at all"); expect_unquote_fail("\"no trailing quote"); expect_unquote_fail("no leading quote\""); expect_unquote_fail("\"invalid \\z escape char\""); expect_unquote_fail("\"\\q invalid escape char\""); expect_unquote_fail("\"invalid escape char \\p\""); expect_unquote_fail("\"invalid \\1 escape char \""); expect_unquote_fail("\"invalid \\14 escape char \""); expect_unquote_fail("\"invalid \\280 escape char\""); expect_unquote_fail("\"invalid \\378 escape char\""); expect_unquote_fail("\"invalid \\380 escape char\""); expect_unquote_fail("\"invalid \\411 escape char\""); expect_unquote_fail("\"truncated escape char \\\""); expect_unquote_fail("\"truncated escape char \\0\""); expect_unquote_fail("\"truncated escape char \\01\""); }
libgit2-main
tests/util/str/quote.c
#include "clar_libgit2.h" static void expect_decode_pass(const char *expected, const char *encoded) { git_str in = GIT_STR_INIT, out = GIT_STR_INIT; /* * ensure that we only read the given length of the input buffer * by putting garbage at the end. this will ensure that we do * not, eg, rely on nul-termination or walk off the end of the buf. */ cl_git_pass(git_str_puts(&in, encoded)); cl_git_pass(git_str_PUTS(&in, "TRAILER")); cl_git_pass(git_str_decode_percent(&out, in.ptr, strlen(encoded))); cl_assert_equal_s(expected, git_str_cstr(&out)); cl_assert_equal_i(strlen(expected), git_str_len(&out)); git_str_dispose(&in); git_str_dispose(&out); } void test_str_percent__decode_succeeds(void) { expect_decode_pass("", ""); expect_decode_pass(" ", "%20"); expect_decode_pass("a", "a"); expect_decode_pass(" a", "%20a"); expect_decode_pass("a ", "a%20"); expect_decode_pass("github.com", "github.com"); expect_decode_pass("github.com", "githu%62.com"); expect_decode_pass("github.com", "github%2ecom"); expect_decode_pass("foo bar baz", "foo%20bar%20baz"); expect_decode_pass("foo bar baz", "foo%20bar%20baz"); expect_decode_pass("foo bar ", "foo%20bar%20"); } void test_str_percent__ignores_invalid(void) { expect_decode_pass("githu%%.com", "githu%%.com"); expect_decode_pass("github.co%2", "github.co%2"); expect_decode_pass("github%2.com", "github%2.com"); expect_decode_pass("githu%2z.com", "githu%2z.com"); expect_decode_pass("github.co%9z", "github.co%9z"); expect_decode_pass("github.co%2", "github.co%2"); expect_decode_pass("github.co%", "github.co%"); }
libgit2-main
tests/util/str/percent.c
/* * Copyright (c) Vicent Marti. All rights reserved. * * This file is part of clar, distributed under the ISC license. * For full terms see the included COPYING file. */ #include <assert.h> #include <setjmp.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <stdarg.h> #include <wchar.h> /* required for sandboxing */ #include <sys/types.h> #include <sys/stat.h> #ifdef _WIN32 # include <windows.h> # include <io.h> # include <shellapi.h> # include <direct.h> # define _MAIN_CC __cdecl # ifndef stat # define stat(path, st) _stat(path, st) # endif # ifndef mkdir # define mkdir(path, mode) _mkdir(path) # endif # ifndef chdir # define chdir(path) _chdir(path) # endif # ifndef access # define access(path, mode) _access(path, mode) # endif # ifndef strdup # define strdup(str) _strdup(str) # endif # ifndef strcasecmp # define strcasecmp(a,b) _stricmp(a,b) # endif # ifndef __MINGW32__ # pragma comment(lib, "shell32") # ifndef strncpy # define strncpy(to, from, to_size) strncpy_s(to, to_size, from, _TRUNCATE) # endif # ifndef W_OK # define W_OK 02 # endif # ifndef S_ISDIR # define S_ISDIR(x) ((x & _S_IFDIR) != 0) # endif # define p_snprintf(buf,sz,fmt,...) _snprintf_s(buf,sz,_TRUNCATE,fmt,__VA_ARGS__) # else # define p_snprintf snprintf # endif # ifndef PRIuZ # define PRIuZ "Iu" # endif # ifndef PRIxZ # define PRIxZ "Ix" # endif # if defined(_MSC_VER) || defined(__MINGW32__) typedef struct stat STAT_T; # else typedef struct _stat STAT_T; # endif #else # include <sys/wait.h> /* waitpid(2) */ # include <unistd.h> # define _MAIN_CC # define p_snprintf snprintf # ifndef PRIuZ # define PRIuZ "zu" # endif # ifndef PRIxZ # define PRIxZ "zx" # endif typedef struct stat STAT_T; #endif #include "clar.h" static void fs_rm(const char *_source); static void fs_copy(const char *_source, const char *dest); static const char * fixture_path(const char *base, const char *fixture_name); struct clar_error { const char *file; const char *function; size_t line_number; const char *error_msg; char *description; struct clar_error *next; }; struct clar_explicit { size_t suite_idx; const char *filter; struct clar_explicit *next; }; struct clar_report { const char *test; int test_number; const char *suite; enum cl_test_status status; struct clar_error *errors; struct clar_error *last_error; struct clar_report *next; }; struct clar_summary { const char *filename; FILE *fp; }; static struct { enum cl_test_status test_status; const char *active_test; const char *active_suite; int total_skipped; int total_errors; int tests_ran; int suites_ran; enum cl_output_format output_format; int report_errors_only; int exit_on_error; int report_suite_names; int write_summary; char *summary_filename; struct clar_summary *summary; struct clar_explicit *explicit; struct clar_explicit *last_explicit; struct clar_report *reports; struct clar_report *last_report; void (*local_cleanup)(void *); void *local_cleanup_payload; jmp_buf trampoline; int trampoline_enabled; cl_trace_cb *pfn_trace_cb; void *trace_payload; } _clar; struct clar_func { const char *name; void (*ptr)(void); }; struct clar_suite { const char *name; struct clar_func initialize; struct clar_func cleanup; const struct clar_func *tests; size_t test_count; int enabled; }; /* From clar_print_*.c */ static void clar_print_init(int test_count, int suite_count, const char *suite_names); static void clar_print_shutdown(int test_count, int suite_count, int error_count); static void clar_print_error(int num, const struct clar_report *report, const struct clar_error *error); static void clar_print_ontest(const char *test_name, int test_number, enum cl_test_status failed); static void clar_print_onsuite(const char *suite_name, int suite_index); static void clar_print_onabort(const char *msg, ...); /* From clar_sandbox.c */ static void clar_unsandbox(void); static int clar_sandbox(void); /* From summary.h */ static struct clar_summary *clar_summary_init(const char *filename); static int clar_summary_shutdown(struct clar_summary *fp); /* Load the declarations for the test suite */ #include "clar.suite" #define CL_TRACE(ev) \ do { \ if (_clar.pfn_trace_cb) \ _clar.pfn_trace_cb(ev, \ _clar.active_suite, \ _clar.active_test, \ _clar.trace_payload); \ } while (0) void cl_trace_register(cl_trace_cb *cb, void *payload) { _clar.pfn_trace_cb = cb; _clar.trace_payload = payload; } /* Core test functions */ static void clar_report_errors(struct clar_report *report) { struct clar_error *error; int i = 1; for (error = report->errors; error; error = error->next) clar_print_error(i++, _clar.last_report, error); } static void clar_report_all(void) { struct clar_report *report; struct clar_error *error; int i = 1; for (report = _clar.reports; report; report = report->next) { if (report->status != CL_TEST_FAILURE) continue; for (error = report->errors; error; error = error->next) clar_print_error(i++, report, error); } } static void clar_run_test( const struct clar_func *test, const struct clar_func *initialize, const struct clar_func *cleanup) { _clar.trampoline_enabled = 1; CL_TRACE(CL_TRACE__TEST__BEGIN); if (setjmp(_clar.trampoline) == 0) { if (initialize->ptr != NULL) initialize->ptr(); CL_TRACE(CL_TRACE__TEST__RUN_BEGIN); test->ptr(); CL_TRACE(CL_TRACE__TEST__RUN_END); } _clar.trampoline_enabled = 0; if (_clar.last_report->status == CL_TEST_NOTRUN) _clar.last_report->status = CL_TEST_OK; if (_clar.local_cleanup != NULL) _clar.local_cleanup(_clar.local_cleanup_payload); if (cleanup->ptr != NULL) cleanup->ptr(); CL_TRACE(CL_TRACE__TEST__END); _clar.tests_ran++; /* remove any local-set cleanup methods */ _clar.local_cleanup = NULL; _clar.local_cleanup_payload = NULL; if (_clar.report_errors_only) { clar_report_errors(_clar.last_report); } else { clar_print_ontest(test->name, _clar.tests_ran, _clar.last_report->status); } } static void clar_run_suite(const struct clar_suite *suite, const char *filter) { const struct clar_func *test = suite->tests; size_t i, matchlen; struct clar_report *report; int exact = 0; if (!suite->enabled) return; if (_clar.exit_on_error && _clar.total_errors) return; if (!_clar.report_errors_only) clar_print_onsuite(suite->name, ++_clar.suites_ran); _clar.active_suite = suite->name; _clar.active_test = NULL; CL_TRACE(CL_TRACE__SUITE_BEGIN); if (filter) { size_t suitelen = strlen(suite->name); matchlen = strlen(filter); if (matchlen <= suitelen) { filter = NULL; } else { filter += suitelen; while (*filter == ':') ++filter; matchlen = strlen(filter); if (matchlen && filter[matchlen - 1] == '$') { exact = 1; matchlen--; } } } for (i = 0; i < suite->test_count; ++i) { if (filter && strncmp(test[i].name, filter, matchlen)) continue; if (exact && strlen(test[i].name) != matchlen) continue; _clar.active_test = test[i].name; report = calloc(1, sizeof(struct clar_report)); report->suite = _clar.active_suite; report->test = _clar.active_test; report->test_number = _clar.tests_ran; report->status = CL_TEST_NOTRUN; if (_clar.reports == NULL) _clar.reports = report; if (_clar.last_report != NULL) _clar.last_report->next = report; _clar.last_report = report; clar_run_test(&test[i], &suite->initialize, &suite->cleanup); if (_clar.exit_on_error && _clar.total_errors) return; } _clar.active_test = NULL; CL_TRACE(CL_TRACE__SUITE_END); } static void clar_usage(const char *arg) { printf("Usage: %s [options]\n\n", arg); printf("Options:\n"); printf(" -sname Run only the suite with `name` (can go to individual test name)\n"); printf(" -iname Include the suite with `name`\n"); printf(" -xname Exclude the suite with `name`\n"); printf(" -v Increase verbosity (show suite names)\n"); printf(" -q Only report tests that had an error\n"); printf(" -Q Quit as soon as a test fails\n"); printf(" -t Display results in tap format\n"); printf(" -l Print suite names\n"); printf(" -r[filename] Write summary file (to the optional filename)\n"); exit(-1); } static void clar_parse_args(int argc, char **argv) { int i; /* Verify options before execute */ for (i = 1; i < argc; ++i) { char *argument = argv[i]; if (argument[0] != '-' || argument[1] == '\0' || strchr("sixvqQtlr", argument[1]) == NULL) { clar_usage(argv[0]); } } for (i = 1; i < argc; ++i) { char *argument = argv[i]; switch (argument[1]) { case 's': case 'i': case 'x': { /* given suite name */ int offset = (argument[2] == '=') ? 3 : 2, found = 0; char action = argument[1]; size_t j, arglen, suitelen, cmplen; argument += offset; arglen = strlen(argument); if (arglen == 0) clar_usage(argv[0]); for (j = 0; j < _clar_suite_count; ++j) { suitelen = strlen(_clar_suites[j].name); cmplen = (arglen < suitelen) ? arglen : suitelen; if (strncmp(argument, _clar_suites[j].name, cmplen) == 0) { int exact = (arglen >= suitelen); /* Do we have a real suite prefix separated by a * trailing '::' or just a matching substring? */ if (arglen > suitelen && (argument[suitelen] != ':' || argument[suitelen + 1] != ':')) continue; ++found; if (!exact) _clar.report_suite_names = 1; switch (action) { case 's': { struct clar_explicit *explicit = calloc(1, sizeof(struct clar_explicit)); assert(explicit); explicit->suite_idx = j; explicit->filter = argument; if (_clar.explicit == NULL) _clar.explicit = explicit; if (_clar.last_explicit != NULL) _clar.last_explicit->next = explicit; _clar_suites[j].enabled = 1; _clar.last_explicit = explicit; break; } case 'i': _clar_suites[j].enabled = 1; break; case 'x': _clar_suites[j].enabled = 0; break; } if (exact) break; } } if (!found) { clar_print_onabort("No suite matching '%s' found.\n", argument); exit(-1); } break; } case 'q': _clar.report_errors_only = 1; break; case 'Q': _clar.exit_on_error = 1; break; case 't': _clar.output_format = CL_OUTPUT_TAP; break; case 'l': { size_t j; printf("Test suites (use -s<name> to run just one):\n"); for (j = 0; j < _clar_suite_count; ++j) printf(" %3d: %s\n", (int)j, _clar_suites[j].name); exit(0); } case 'v': _clar.report_suite_names = 1; break; case 'r': _clar.write_summary = 1; free(_clar.summary_filename); _clar.summary_filename = strdup(*(argument + 2) ? (argument + 2) : "summary.xml"); break; default: assert(!"Unexpected commandline argument!"); } } } void clar_test_init(int argc, char **argv) { if (argc > 1) clar_parse_args(argc, argv); clar_print_init( (int)_clar_callback_count, (int)_clar_suite_count, "" ); if ((_clar.summary_filename = getenv("CLAR_SUMMARY")) != NULL) { _clar.write_summary = 1; _clar.summary_filename = strdup(_clar.summary_filename); } if (_clar.write_summary && !(_clar.summary = clar_summary_init(_clar.summary_filename))) { clar_print_onabort("Failed to open the summary file\n"); exit(-1); } if (clar_sandbox() < 0) { clar_print_onabort("Failed to sandbox the test runner.\n"); exit(-1); } } int clar_test_run(void) { size_t i; struct clar_explicit *explicit; if (_clar.explicit) { for (explicit = _clar.explicit; explicit; explicit = explicit->next) clar_run_suite(&_clar_suites[explicit->suite_idx], explicit->filter); } else { for (i = 0; i < _clar_suite_count; ++i) clar_run_suite(&_clar_suites[i], NULL); } return _clar.total_errors; } void clar_test_shutdown(void) { struct clar_explicit *explicit, *explicit_next; struct clar_report *report, *report_next; clar_print_shutdown( _clar.tests_ran, (int)_clar_suite_count, _clar.total_errors ); clar_unsandbox(); if (_clar.write_summary && clar_summary_shutdown(_clar.summary) < 0) { clar_print_onabort("Failed to write the summary file\n"); exit(-1); } for (explicit = _clar.explicit; explicit; explicit = explicit_next) { explicit_next = explicit->next; free(explicit); } for (report = _clar.reports; report; report = report_next) { report_next = report->next; free(report); } free(_clar.summary_filename); } int clar_test(int argc, char **argv) { int errors; clar_test_init(argc, argv); errors = clar_test_run(); clar_test_shutdown(); return errors; } static void abort_test(void) { if (!_clar.trampoline_enabled) { clar_print_onabort( "Fatal error: a cleanup method raised an exception."); clar_report_errors(_clar.last_report); exit(-1); } CL_TRACE(CL_TRACE__TEST__LONGJMP); longjmp(_clar.trampoline, -1); } void clar__skip(void) { _clar.last_report->status = CL_TEST_SKIP; _clar.total_skipped++; abort_test(); } void clar__fail( const char *file, const char *function, size_t line, const char *error_msg, const char *description, int should_abort) { struct clar_error *error = calloc(1, sizeof(struct clar_error)); if (_clar.last_report->errors == NULL) _clar.last_report->errors = error; if (_clar.last_report->last_error != NULL) _clar.last_report->last_error->next = error; _clar.last_report->last_error = error; error->file = file; error->function = function; error->line_number = line; error->error_msg = error_msg; if (description != NULL) error->description = strdup(description); _clar.total_errors++; _clar.last_report->status = CL_TEST_FAILURE; if (should_abort) abort_test(); } void clar__assert( int condition, const char *file, const char *function, size_t line, const char *error_msg, const char *description, int should_abort) { if (condition) return; clar__fail(file, function, line, error_msg, description, should_abort); } void clar__assert_equal( const char *file, const char *function, size_t line, const char *err, int should_abort, const char *fmt, ...) { va_list args; char buf[4096]; int is_equal = 1; va_start(args, fmt); if (!strcmp("%s", fmt)) { const char *s1 = va_arg(args, const char *); const char *s2 = va_arg(args, const char *); is_equal = (!s1 || !s2) ? (s1 == s2) : !strcmp(s1, s2); if (!is_equal) { if (s1 && s2) { int pos; for (pos = 0; s1[pos] == s2[pos] && s1[pos] && s2[pos]; ++pos) /* find differing byte offset */; p_snprintf(buf, sizeof(buf), "'%s' != '%s' (at byte %d)", s1, s2, pos); } else { p_snprintf(buf, sizeof(buf), "'%s' != '%s'", s1, s2); } } } else if(!strcmp("%.*s", fmt)) { const char *s1 = va_arg(args, const char *); const char *s2 = va_arg(args, const char *); int len = va_arg(args, int); is_equal = (!s1 || !s2) ? (s1 == s2) : !strncmp(s1, s2, len); if (!is_equal) { if (s1 && s2) { int pos; for (pos = 0; s1[pos] == s2[pos] && pos < len; ++pos) /* find differing byte offset */; p_snprintf(buf, sizeof(buf), "'%.*s' != '%.*s' (at byte %d)", len, s1, len, s2, pos); } else { p_snprintf(buf, sizeof(buf), "'%.*s' != '%.*s'", len, s1, len, s2); } } } else if (!strcmp("%ls", fmt)) { const wchar_t *wcs1 = va_arg(args, const wchar_t *); const wchar_t *wcs2 = va_arg(args, const wchar_t *); is_equal = (!wcs1 || !wcs2) ? (wcs1 == wcs2) : !wcscmp(wcs1, wcs2); if (!is_equal) { if (wcs1 && wcs2) { int pos; for (pos = 0; wcs1[pos] == wcs2[pos] && wcs1[pos] && wcs2[pos]; ++pos) /* find differing byte offset */; p_snprintf(buf, sizeof(buf), "'%ls' != '%ls' (at byte %d)", wcs1, wcs2, pos); } else { p_snprintf(buf, sizeof(buf), "'%ls' != '%ls'", wcs1, wcs2); } } } else if(!strcmp("%.*ls", fmt)) { const wchar_t *wcs1 = va_arg(args, const wchar_t *); const wchar_t *wcs2 = va_arg(args, const wchar_t *); int len = va_arg(args, int); is_equal = (!wcs1 || !wcs2) ? (wcs1 == wcs2) : !wcsncmp(wcs1, wcs2, len); if (!is_equal) { if (wcs1 && wcs2) { int pos; for (pos = 0; wcs1[pos] == wcs2[pos] && pos < len; ++pos) /* find differing byte offset */; p_snprintf(buf, sizeof(buf), "'%.*ls' != '%.*ls' (at byte %d)", len, wcs1, len, wcs2, pos); } else { p_snprintf(buf, sizeof(buf), "'%.*ls' != '%.*ls'", len, wcs1, len, wcs2); } } } else if (!strcmp("%"PRIuZ, fmt) || !strcmp("%"PRIxZ, fmt)) { size_t sz1 = va_arg(args, size_t), sz2 = va_arg(args, size_t); is_equal = (sz1 == sz2); if (!is_equal) { int offset = p_snprintf(buf, sizeof(buf), fmt, sz1); strncat(buf, " != ", sizeof(buf) - offset); p_snprintf(buf + offset + 4, sizeof(buf) - offset - 4, fmt, sz2); } } else if (!strcmp("%p", fmt)) { void *p1 = va_arg(args, void *), *p2 = va_arg(args, void *); is_equal = (p1 == p2); if (!is_equal) p_snprintf(buf, sizeof(buf), "%p != %p", p1, p2); } else { int i1 = va_arg(args, int), i2 = va_arg(args, int); is_equal = (i1 == i2); if (!is_equal) { int offset = p_snprintf(buf, sizeof(buf), fmt, i1); strncat(buf, " != ", sizeof(buf) - offset); p_snprintf(buf + offset + 4, sizeof(buf) - offset - 4, fmt, i2); } } va_end(args); if (!is_equal) clar__fail(file, function, line, err, buf, should_abort); } void cl_set_cleanup(void (*cleanup)(void *), void *opaque) { _clar.local_cleanup = cleanup; _clar.local_cleanup_payload = opaque; } #include "clar/sandbox.h" #include "clar/fixtures.h" #include "clar/fs.h" #include "clar/print.h" #include "clar/summary.h"
libgit2-main
tests/clar/clar.c
#include "clar_libgit2.h" #include "posix.h" #include "fs_path.h" #include "git2/sys/repository.h" void cl_git_report_failure( int error, int expected, const char *file, const char *func, int line, const char *fncall) { char msg[4096]; const git_error *last = git_error_last(); if (expected) p_snprintf(msg, 4096, "error %d (expected %d) - %s", error, expected, last ? last->message : "<no message>"); else if (error || last) p_snprintf(msg, 4096, "error %d - %s", error, last ? last->message : "<no message>"); else p_snprintf(msg, 4096, "no error, expected non-zero return"); clar__assert(0, file, func, line, fncall, msg, 1); } void cl_git_mkfile(const char *filename, const char *content) { int fd; fd = p_creat(filename, 0666); cl_assert(fd != -1); if (content) { cl_must_pass(p_write(fd, content, strlen(content))); } else { cl_must_pass(p_write(fd, filename, strlen(filename))); cl_must_pass(p_write(fd, "\n", 1)); } cl_must_pass(p_close(fd)); } void cl_git_write2file( const char *path, const char *content, size_t content_len, int flags, unsigned int mode) { int fd; cl_assert(path && content); cl_assert((fd = p_open(path, flags, mode)) >= 0); if (!content_len) content_len = strlen(content); cl_must_pass(p_write(fd, content, content_len)); cl_must_pass(p_close(fd)); } void cl_git_append2file(const char *path, const char *content) { cl_git_write2file(path, content, 0, O_WRONLY | O_CREAT | O_APPEND, 0644); } void cl_git_rewritefile(const char *path, const char *content) { cl_git_write2file(path, content, 0, O_WRONLY | O_CREAT | O_TRUNC, 0644); } void cl_git_rmfile(const char *filename) { cl_must_pass(p_unlink(filename)); } char *cl_getenv(const char *name) { git_str out = GIT_STR_INIT; int error = git__getenv(&out, name); cl_assert(error >= 0 || error == GIT_ENOTFOUND); if (error == GIT_ENOTFOUND) return NULL; if (out.size == 0) { char *dup = git__strdup(""); cl_assert(dup); return dup; } return git_str_detach(&out); } bool cl_is_env_set(const char *name) { char *env = cl_getenv(name); bool result = (env != NULL); git__free(env); return result; } #ifdef GIT_WIN32 #include "win32/utf-conv.h" int cl_setenv(const char *name, const char *value) { wchar_t *wide_name, *wide_value = NULL; cl_assert(git__utf8_to_16_alloc(&wide_name, name) >= 0); if (value) { cl_assert(git__utf8_to_16_alloc(&wide_value, value) >= 0); cl_assert(SetEnvironmentVariableW(wide_name, wide_value)); } else { /* Windows XP returns 0 (failed) when passing NULL for lpValue when * lpName does not exist in the environment block. This behavior * seems to have changed in later versions. Don't check the return value * of SetEnvironmentVariable when passing NULL for lpValue. */ SetEnvironmentVariableW(wide_name, NULL); } git__free(wide_name); git__free(wide_value); return 0; } /* This function performs retries on calls to MoveFile in order * to provide enhanced reliability in the face of antivirus * agents that may be scanning the source (or in the case that * the source is a directory, a child of the source). */ int cl_rename(const char *source, const char *dest) { git_win32_path source_utf16; git_win32_path dest_utf16; unsigned retries = 1; cl_assert(git_win32_path_from_utf8(source_utf16, source) >= 0); cl_assert(git_win32_path_from_utf8(dest_utf16, dest) >= 0); while (!MoveFileW(source_utf16, dest_utf16)) { /* Only retry if the error is ERROR_ACCESS_DENIED; * this may indicate that an antivirus agent is * preventing the rename from source to target */ if (retries > 5 || ERROR_ACCESS_DENIED != GetLastError()) return -1; /* With 5 retries and a coefficient of 10ms, the maximum * delay here is 550 ms */ Sleep(10 * retries * retries); retries++; } return 0; } #else #include <stdlib.h> int cl_setenv(const char *name, const char *value) { return (value == NULL) ? unsetenv(name) : setenv(name, value, 1); } int cl_rename(const char *source, const char *dest) { return p_rename(source, dest); } #endif static const char *_cl_sandbox = NULL; static git_repository *_cl_repo = NULL; git_repository *cl_git_sandbox_init(const char *sandbox) { /* Get the name of the sandbox folder which will be created */ const char *basename = cl_fixture_basename(sandbox); /* Copy the whole sandbox folder from our fixtures to our test sandbox * area. After this it can be accessed with `./sandbox` */ cl_fixture_sandbox(sandbox); _cl_sandbox = sandbox; cl_git_pass(p_chdir(basename)); /* If this is not a bare repo, then rename `sandbox/.gitted` to * `sandbox/.git` which must be done since we cannot store a folder * named `.git` inside the fixtures folder of our libgit2 repo. */ if (p_access(".gitted", F_OK) == 0) cl_git_pass(cl_rename(".gitted", ".git")); /* If we have `gitattributes`, rename to `.gitattributes`. This may * be necessary if we don't want the attributes to be applied in the * libgit2 repo, but just during testing. */ if (p_access("gitattributes", F_OK) == 0) cl_git_pass(cl_rename("gitattributes", ".gitattributes")); /* As with `gitattributes`, we may need `gitignore` just for testing. */ if (p_access("gitignore", F_OK) == 0) cl_git_pass(cl_rename("gitignore", ".gitignore")); cl_git_pass(p_chdir("..")); /* Now open the sandbox repository and make it available for tests */ cl_git_pass(git_repository_open(&_cl_repo, basename)); /* Adjust configs after copying to new filesystem */ cl_git_pass(git_repository_reinit_filesystem(_cl_repo, 0)); return _cl_repo; } git_repository *cl_git_sandbox_init_new(const char *sandbox) { cl_git_pass(git_repository_init(&_cl_repo, sandbox, false)); _cl_sandbox = sandbox; return _cl_repo; } git_repository *cl_git_sandbox_reopen(void) { if (_cl_repo) { git_repository_free(_cl_repo); _cl_repo = NULL; cl_git_pass(git_repository_open( &_cl_repo, cl_fixture_basename(_cl_sandbox))); } return _cl_repo; } void cl_git_sandbox_cleanup(void) { if (_cl_repo) { git_repository_free(_cl_repo); _cl_repo = NULL; } if (_cl_sandbox) { cl_fixture_cleanup(_cl_sandbox); _cl_sandbox = NULL; } } bool cl_toggle_filemode(const char *filename) { struct stat st1, st2; cl_must_pass(p_stat(filename, &st1)); cl_must_pass(p_chmod(filename, st1.st_mode ^ 0100)); cl_must_pass(p_stat(filename, &st2)); return (st1.st_mode != st2.st_mode); } bool cl_is_chmod_supported(void) { static int _is_supported = -1; if (_is_supported < 0) { cl_git_mkfile("filemode.t", "Test if filemode can be modified"); _is_supported = cl_toggle_filemode("filemode.t"); cl_must_pass(p_unlink("filemode.t")); } return _is_supported; } const char* cl_git_fixture_url(const char *fixturename) { return cl_git_path_url(cl_fixture(fixturename)); } const char* cl_git_path_url(const char *path) { static char url[4096 + 1]; const char *in_buf; git_str path_buf = GIT_STR_INIT; git_str url_buf = GIT_STR_INIT; cl_git_pass(git_fs_path_prettify_dir(&path_buf, path, NULL)); cl_git_pass(git_str_puts(&url_buf, "file://")); #ifdef GIT_WIN32 /* * A FILE uri matches the following format: file://[host]/path * where "host" can be empty and "path" is an absolute path to the resource. * * In this test, no hostname is used, but we have to ensure the leading triple slashes: * * *nix: file:///usr/home/... * Windows: file:///C:/Users/... */ cl_git_pass(git_str_putc(&url_buf, '/')); #endif in_buf = git_str_cstr(&path_buf); /* * A very hacky Url encoding that only takes care of escaping the spaces */ while (*in_buf) { if (*in_buf == ' ') cl_git_pass(git_str_puts(&url_buf, "%20")); else cl_git_pass(git_str_putc(&url_buf, *in_buf)); in_buf++; } cl_assert(url_buf.size < sizeof(url) - 1); strncpy(url, git_str_cstr(&url_buf), sizeof(url) - 1); url[sizeof(url) - 1] = '\0'; git_str_dispose(&url_buf); git_str_dispose(&path_buf); return url; } const char *cl_git_sandbox_path(int is_dir, ...) { const char *path = NULL; static char _temp[GIT_PATH_MAX]; git_str buf = GIT_STR_INIT; va_list arg; cl_git_pass(git_str_sets(&buf, clar_sandbox_path())); va_start(arg, is_dir); while ((path = va_arg(arg, const char *)) != NULL) { cl_git_pass(git_str_joinpath(&buf, buf.ptr, path)); } va_end(arg); cl_git_pass(git_fs_path_prettify(&buf, buf.ptr, NULL)); if (is_dir) git_fs_path_to_dir(&buf); /* make sure we won't truncate */ cl_assert(git_str_len(&buf) < sizeof(_temp)); git_str_copy_cstr(_temp, sizeof(_temp), &buf); git_str_dispose(&buf); return _temp; } typedef struct { const char *filename; size_t filename_len; } remove_data; static int remove_placeholders_recurs(void *_data, git_str *path) { remove_data *data = (remove_data *)_data; size_t pathlen; if (git_fs_path_isdir(path->ptr) == true) return git_fs_path_direach(path, 0, remove_placeholders_recurs, data); pathlen = path->size; if (pathlen < data->filename_len) return 0; /* if path ends in '/'+filename (or equals filename) */ if (!strcmp(data->filename, path->ptr + pathlen - data->filename_len) && (pathlen == data->filename_len || path->ptr[pathlen - data->filename_len - 1] == '/')) return p_unlink(path->ptr); return 0; } int cl_git_remove_placeholders(const char *directory_path, const char *filename) { int error; remove_data data; git_str buffer = GIT_STR_INIT; if (git_fs_path_isdir(directory_path) == false) return -1; if (git_str_sets(&buffer, directory_path) < 0) return -1; data.filename = filename; data.filename_len = strlen(filename); error = remove_placeholders_recurs(&data, &buffer); git_str_dispose(&buffer); return error; } #define CL_COMMIT_NAME "Libgit2 Tester" #define CL_COMMIT_EMAIL "[email protected]" #define CL_COMMIT_MSG "Test commit of tree " void cl_repo_commit_from_index( git_oid *out, git_repository *repo, git_signature *sig, git_time_t time, const char *msg) { git_index *index; git_oid commit_id, tree_id; git_object *parent = NULL; git_reference *ref = NULL; git_tree *tree = NULL; char buf[128]; int free_sig = (sig == NULL); /* it is fine if looking up HEAD fails - we make this the first commit */ git_revparse_ext(&parent, &ref, repo, "HEAD"); /* write the index content as a tree */ cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_index_write_tree(&tree_id, index)); cl_git_pass(git_index_write(index)); git_index_free(index); cl_git_pass(git_tree_lookup(&tree, repo, &tree_id)); if (sig) cl_assert(sig->name && sig->email); else if (!time) cl_git_pass(git_signature_now(&sig, CL_COMMIT_NAME, CL_COMMIT_EMAIL)); else cl_git_pass(git_signature_new( &sig, CL_COMMIT_NAME, CL_COMMIT_EMAIL, time, 0)); if (!msg) { strcpy(buf, CL_COMMIT_MSG); git_oid_tostr(buf + strlen(CL_COMMIT_MSG), sizeof(buf) - strlen(CL_COMMIT_MSG), &tree_id); msg = buf; } cl_git_pass(git_commit_create_v( &commit_id, repo, ref ? git_reference_name(ref) : "HEAD", sig, sig, NULL, msg, tree, parent ? 1 : 0, parent)); if (out) git_oid_cpy(out, &commit_id); git_object_free(parent); git_reference_free(ref); if (free_sig) git_signature_free(sig); git_tree_free(tree); } void cl_repo_set_bool(git_repository *repo, const char *cfg, int value) { git_config *config; cl_git_pass(git_repository_config(&config, repo)); cl_git_pass(git_config_set_bool(config, cfg, value != 0)); git_config_free(config); } int cl_repo_get_bool(git_repository *repo, const char *cfg) { int val = 0; git_config *config; cl_git_pass(git_repository_config(&config, repo)); if (git_config_get_bool(&val, config, cfg) < 0) git_error_clear(); git_config_free(config); return val; } void cl_repo_set_string(git_repository *repo, const char *cfg, const char *value) { git_config *config; cl_git_pass(git_repository_config(&config, repo)); cl_git_pass(git_config_set_string(config, cfg, value)); git_config_free(config); } /* this is essentially the code from git__unescape modified slightly */ static size_t strip_cr_from_buf(char *start, size_t len) { char *scan, *trail, *end = start + len; for (scan = trail = start; scan < end; trail++, scan++) { while (*scan == '\r') scan++; /* skip '\r' */ if (trail != scan) *trail = *scan; } *trail = '\0'; return (trail - start); } void clar__assert_equal_file( const char *expected_data, size_t expected_bytes, int ignore_cr, const char *path, const char *file, const char *func, int line) { char buf[4000]; ssize_t bytes, total_bytes = 0; int fd = p_open(path, O_RDONLY | O_BINARY); cl_assert(fd >= 0); if (expected_data && !expected_bytes) expected_bytes = strlen(expected_data); while ((bytes = p_read(fd, buf, sizeof(buf))) != 0) { clar__assert( bytes > 0, file, func, line, "error reading from file", path, 1); if (ignore_cr) bytes = strip_cr_from_buf(buf, bytes); if (memcmp(expected_data, buf, bytes) != 0) { int pos; for (pos = 0; pos < bytes && expected_data[pos] == buf[pos]; ++pos) /* find differing byte offset */; p_snprintf( buf, sizeof(buf), "file content mismatch at byte %"PRIdZ, (ssize_t)(total_bytes + pos)); p_close(fd); clar__fail(file, func, line, path, buf, 1); } expected_data += bytes; total_bytes += bytes; } p_close(fd); clar__assert(!bytes, file, func, line, "error reading from file", path, 1); clar__assert_equal(file, func, line, "mismatched file length", 1, "%"PRIuZ, (size_t)expected_bytes, (size_t)total_bytes); } static git_buf _cl_restore_home = GIT_BUF_INIT; void cl_fake_home_cleanup(void *payload) { GIT_UNUSED(payload); if (_cl_restore_home.ptr) { cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, _cl_restore_home.ptr)); git_buf_dispose(&_cl_restore_home); } } void cl_fake_home(void) { git_str path = GIT_STR_INIT; cl_git_pass(git_libgit2_opts( GIT_OPT_GET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, &_cl_restore_home)); cl_set_cleanup(cl_fake_home_cleanup, NULL); if (!git_fs_path_exists("home")) cl_must_pass(p_mkdir("home", 0777)); cl_git_pass(git_fs_path_prettify(&path, "home", NULL)); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, path.ptr)); git_str_dispose(&path); } void cl_sandbox_set_search_path_defaults(void) { git_str path = GIT_STR_INIT; git_str_joinpath(&path, clar_sandbox_path(), "__config"); if (!git_fs_path_exists(path.ptr)) cl_must_pass(p_mkdir(path.ptr, 0777)); git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, path.ptr); git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_XDG, path.ptr); git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_SYSTEM, path.ptr); git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_PROGRAMDATA, path.ptr); git_str_dispose(&path); } void cl_sandbox_disable_ownership_validation(void) { git_libgit2_opts(GIT_OPT_SET_OWNER_VALIDATION, 0); } #ifdef GIT_WIN32 bool cl_sandbox_supports_8dot3(void) { git_str longpath = GIT_STR_INIT; char *shortname; bool supported; cl_git_pass( git_str_joinpath(&longpath, clar_sandbox_path(), "longer_than_8dot3")); cl_git_write2file(longpath.ptr, "", 0, O_RDWR|O_CREAT, 0666); shortname = git_win32_path_8dot3_name(longpath.ptr); supported = (shortname != NULL); git__free(shortname); git_str_dispose(&longpath); return supported; } #endif
libgit2-main
tests/clar/clar_libgit2.c
#include "clar_libgit2.h" #include "clar_libgit2_trace.h" #ifdef GIT_WIN32_LEAKCHECK # include "win32/w32_leakcheck.h" #endif #ifdef _WIN32 int __cdecl main(int argc, char *argv[]) #else int main(int argc, char *argv[]) #endif { int res; char *at_exit_cmd; clar_test_init(argc, argv); res = git_libgit2_init(); if (res < 0) { const git_error *err = git_error_last(); const char *msg = err ? err->message : "unknown failure"; fprintf(stderr, "failed to init libgit2: %s\n", msg); return res; } cl_global_trace_register(); cl_sandbox_set_search_path_defaults(); cl_sandbox_disable_ownership_validation(); /* Run the test suite */ res = clar_test_run(); clar_test_shutdown(); cl_global_trace_disable(); git_libgit2_shutdown(); #ifdef GIT_WIN32_LEAKCHECK if (git_win32_leakcheck_has_leaks()) res = res || 1; #endif at_exit_cmd = getenv("CLAR_AT_EXIT"); if (at_exit_cmd != NULL) { int at_exit = system(at_exit_cmd); return res || at_exit; } return res; }
libgit2-main
tests/clar/main.c
#include "clar_libgit2_trace.h" #include "clar_libgit2.h" #include "clar_libgit2_timer.h" #include "trace.h" struct method { const char *name; void (*git_trace_cb)(git_trace_level_t level, const char *msg); void (*close)(void); }; static const char *message_prefix(git_trace_level_t level) { switch (level) { case GIT_TRACE_NONE: return "[NONE]: "; case GIT_TRACE_FATAL: return "[FATAL]: "; case GIT_TRACE_ERROR: return "[ERROR]: "; case GIT_TRACE_WARN: return "[WARN]: "; case GIT_TRACE_INFO: return "[INFO]: "; case GIT_TRACE_DEBUG: return "[DEBUG]: "; case GIT_TRACE_TRACE: return "[TRACE]: "; default: return "[?????]: "; } } static void _git_trace_cb__printf(git_trace_level_t level, const char *msg) { printf("%s%s\n", message_prefix(level), msg); } #if defined(GIT_WIN32) static void _git_trace_cb__debug(git_trace_level_t level, const char *msg) { OutputDebugString(message_prefix(level)); OutputDebugString(msg); OutputDebugString("\n"); printf("%s%s\n", message_prefix(level), msg); } #else #define _git_trace_cb__debug _git_trace_cb__printf #endif static void _trace_printf_close(void) { fflush(stdout); } #define _trace_debug_close _trace_printf_close static struct method s_methods[] = { { "printf", _git_trace_cb__printf, _trace_printf_close }, { "debug", _git_trace_cb__debug, _trace_debug_close }, /* TODO add file method */ {0}, }; static int s_trace_loaded = 0; static int s_trace_level = GIT_TRACE_NONE; static struct method *s_trace_method = NULL; static int s_trace_tests = 0; static int set_method(const char *name) { int k; if (!name || !*name) name = "printf"; for (k=0; (s_methods[k].name); k++) { if (strcmp(name, s_methods[k].name) == 0) { s_trace_method = &s_methods[k]; return 0; } } fprintf(stderr, "Unknown CLAR_TRACE_METHOD: '%s'\n", name); return -1; } /** * Lookup CLAR_TRACE_LEVEL and CLAR_TRACE_METHOD from * the environment and set the above s_trace_* fields. * * If CLAR_TRACE_LEVEL is not set, we disable tracing. * * TODO If set, we assume GIT_TRACE_TRACE level, which * logs everything. Later, we may want to parse the * value of the environment variable and set a specific * level. * * We assume the "printf" method. This can be changed * with the CLAR_TRACE_METHOD environment variable. * Currently, this is only needed on Windows for a "debug" * version which also writes to the debug output window * in Visual Studio. * * TODO add a "file" method that would open and write * to a well-known file. This would help keep trace * output and clar output separate. * */ static void _load_trace_params(void) { char *sz_level; char *sz_method; char *sz_tests; s_trace_loaded = 1; sz_level = cl_getenv("CLAR_TRACE_LEVEL"); if (!sz_level || !*sz_level) { s_trace_level = GIT_TRACE_NONE; s_trace_method = NULL; return; } /* TODO Parse sz_level and set s_trace_level. */ s_trace_level = GIT_TRACE_TRACE; sz_method = cl_getenv("CLAR_TRACE_METHOD"); if (set_method(sz_method) < 0) set_method(NULL); sz_tests = cl_getenv("CLAR_TRACE_TESTS"); if (sz_tests != NULL) s_trace_tests = 1; } #define HR "================================================================" /** * Timer to report the take spend in a test's run() method. */ static cl_perf_timer s_timer_run = CL_PERF_TIMER_INIT; /** * Timer to report total time in a test (init, run, cleanup). */ static cl_perf_timer s_timer_test = CL_PERF_TIMER_INIT; static void _cl_trace_cb__event_handler( cl_trace_event ev, const char *suite_name, const char *test_name, void *payload) { GIT_UNUSED(payload); if (!s_trace_tests) return; switch (ev) { case CL_TRACE__SUITE_BEGIN: git_trace(GIT_TRACE_TRACE, "\n\n%s\n%s: Begin Suite", HR, suite_name); #if 0 && defined(GIT_WIN32_LEAKCHECK) git_win32__crtdbg_stacktrace__dump( GIT_WIN32__CRTDBG_STACKTRACE__SET_MARK, suite_name); #endif break; case CL_TRACE__SUITE_END: #if 0 && defined(GIT_WIN32_LEAKCHECK) /* As an example of checkpointing, dump leaks within this suite. * This may generate false positives for things like the global * TLS error state and maybe the odb cache since they aren't * freed until the global shutdown and outside the scope of this * set of tests. * * This may under-report if the test itself uses a checkpoint. * See tests/trace/windows/stacktrace.c */ git_win32__crtdbg_stacktrace__dump( GIT_WIN32__CRTDBG_STACKTRACE__LEAKS_SINCE_MARK, suite_name); #endif git_trace(GIT_TRACE_TRACE, "\n\n%s: End Suite\n%s", suite_name, HR); break; case CL_TRACE__TEST__BEGIN: git_trace(GIT_TRACE_TRACE, "\n%s::%s: Begin Test", suite_name, test_name); cl_perf_timer__init(&s_timer_test); cl_perf_timer__start(&s_timer_test); break; case CL_TRACE__TEST__END: cl_perf_timer__stop(&s_timer_test); git_trace(GIT_TRACE_TRACE, "%s::%s: End Test (%.3f %.3f)", suite_name, test_name, cl_perf_timer__last(&s_timer_run), cl_perf_timer__last(&s_timer_test)); break; case CL_TRACE__TEST__RUN_BEGIN: git_trace(GIT_TRACE_TRACE, "%s::%s: Begin Run", suite_name, test_name); cl_perf_timer__init(&s_timer_run); cl_perf_timer__start(&s_timer_run); break; case CL_TRACE__TEST__RUN_END: cl_perf_timer__stop(&s_timer_run); git_trace(GIT_TRACE_TRACE, "%s::%s: End Run", suite_name, test_name); break; case CL_TRACE__TEST__LONGJMP: cl_perf_timer__stop(&s_timer_run); git_trace(GIT_TRACE_TRACE, "%s::%s: Aborted", suite_name, test_name); break; default: break; } } /** * Setup/Enable git_trace() based upon settings user's environment. */ void cl_global_trace_register(void) { if (!s_trace_loaded) _load_trace_params(); if (s_trace_level == GIT_TRACE_NONE) return; if (s_trace_method == NULL) return; if (s_trace_method->git_trace_cb == NULL) return; git_trace_set(s_trace_level, s_trace_method->git_trace_cb); cl_trace_register(_cl_trace_cb__event_handler, NULL); } /** * If we turned on git_trace() earlier, turn it off. * * This is intended to let us close/flush any buffered * IO if necessary. * */ void cl_global_trace_disable(void) { cl_trace_register(NULL, NULL); git_trace_set(GIT_TRACE_NONE, NULL); if (s_trace_method && s_trace_method->close) s_trace_method->close(); /* Leave s_trace_ vars set so they can restart tracing * since we only want to hit the environment variables * once. */ }
libgit2-main
tests/clar/clar_libgit2_trace.c
#include "clar_libgit2.h" #include "clar_libgit2_timer.h" void cl_perf_timer__init(cl_perf_timer *t) { memset(t, 0, sizeof(cl_perf_timer)); } void cl_perf_timer__start(cl_perf_timer *t) { t->time_started = git__timer(); } void cl_perf_timer__stop(cl_perf_timer *t) { double time_now = git__timer(); t->last = time_now - t->time_started; t->sum += t->last; } double cl_perf_timer__last(const cl_perf_timer *t) { return t->last; } double cl_perf_timer__sum(const cl_perf_timer *t) { return t->sum; }
libgit2-main
tests/clar/clar_libgit2_timer.c
#include "precompiled.h"
libgit2-main
tests/libgit2/precompiled.c
#include "clar_libgit2.h" static git_repository *_repo; static git_commit *commit; void test_commit_parent__initialize(void) { git_oid oid; cl_git_pass(git_repository_open(&_repo, cl_fixture("testrepo.git"))); git_oid__fromstr(&oid, "be3563ae3f795b2b4353bcce3a527ad0a4f7f644", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, _repo, &oid)); } void test_commit_parent__cleanup(void) { git_commit_free(commit); commit = NULL; git_repository_free(_repo); _repo = NULL; } static void assert_nth_gen_parent(unsigned int gen, const char *expected_oid) { git_commit *parent = NULL; int error; error = git_commit_nth_gen_ancestor(&parent, commit, gen); if (expected_oid != NULL) { cl_assert_equal_i(0, error); cl_assert_equal_i(0, git_oid_streq(git_commit_id(parent), expected_oid)); } else cl_assert_equal_i(GIT_ENOTFOUND, error); git_commit_free(parent); } /* * $ git show be35~0 * commit be3563ae3f795b2b4353bcce3a527ad0a4f7f644 * * $ git show be35~1 * commit 9fd738e8f7967c078dceed8190330fc8648ee56a * * $ git show be35~3 * commit 5b5b025afb0b4c913b4c338a42934a3863bf3644 * * $ git show be35~42 * fatal: ambiguous argument 'be35~42': unknown revision or path not in the working tree. */ void test_commit_parent__can_retrieve_nth_generation_parent(void) { assert_nth_gen_parent(0, "be3563ae3f795b2b4353bcce3a527ad0a4f7f644"); assert_nth_gen_parent(1, "9fd738e8f7967c078dceed8190330fc8648ee56a"); assert_nth_gen_parent(3, "5b5b025afb0b4c913b4c338a42934a3863bf3644"); assert_nth_gen_parent(42, NULL); }
libgit2-main
tests/libgit2/commit/parent.c
#include "clar_libgit2.h" #include "commit.h" #include "git2/commit.h" static git_repository *_repo; void test_commit_commit__initialize(void) { cl_fixture_sandbox("testrepo.git"); cl_git_pass(git_repository_open(&_repo, "testrepo.git")); } void test_commit_commit__cleanup(void) { git_repository_free(_repo); _repo = NULL; cl_fixture_cleanup("testrepo.git"); } void test_commit_commit__create_unexisting_update_ref(void) { git_oid oid; git_tree *tree; git_commit *commit; git_signature *s; git_reference *ref; git_oid__fromstr(&oid, "a65fedf39aefe402d3bb6e24df4d4f5fe4547750", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, _repo, &oid)); git_oid__fromstr(&oid, "944c0f6e4dfa41595e6eb3ceecdb14f50fe18162", GIT_OID_SHA1); cl_git_pass(git_tree_lookup(&tree, _repo, &oid)); cl_git_pass(git_signature_now(&s, "alice", "[email protected]")); cl_git_fail(git_reference_lookup(&ref, _repo, "refs/heads/foo/bar")); cl_git_pass(git_commit_create(&oid, _repo, "refs/heads/foo/bar", s, s, NULL, "some msg", tree, 1, (const git_commit **) &commit)); /* fail because the parent isn't the tip of the branch anymore */ cl_git_fail(git_commit_create(&oid, _repo, "refs/heads/foo/bar", s, s, NULL, "some msg", tree, 1, (const git_commit **) &commit)); cl_git_pass(git_reference_lookup(&ref, _repo, "refs/heads/foo/bar")); cl_assert_equal_oid(&oid, git_reference_target(ref)); git_tree_free(tree); git_commit_free(commit); git_signature_free(s); git_reference_free(ref); } void test_commit_commit__create_initial_commit(void) { git_oid oid; git_tree *tree; git_commit *commit; git_signature *s; git_reference *ref; git_oid__fromstr(&oid, "a65fedf39aefe402d3bb6e24df4d4f5fe4547750", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, _repo, &oid)); git_oid__fromstr(&oid, "944c0f6e4dfa41595e6eb3ceecdb14f50fe18162", GIT_OID_SHA1); cl_git_pass(git_tree_lookup(&tree, _repo, &oid)); cl_git_pass(git_signature_now(&s, "alice", "[email protected]")); cl_git_fail(git_reference_lookup(&ref, _repo, "refs/heads/foo/bar")); cl_git_pass(git_commit_create(&oid, _repo, "refs/heads/foo/bar", s, s, NULL, "initial commit", tree, 0, NULL)); cl_git_pass(git_reference_lookup(&ref, _repo, "refs/heads/foo/bar")); cl_assert_equal_oid(&oid, git_reference_target(ref)); git_tree_free(tree); git_commit_free(commit); git_signature_free(s); git_reference_free(ref); } void test_commit_commit__create_initial_commit_parent_not_current(void) { git_oid oid; git_oid original_oid; git_tree *tree; git_commit *commit; git_signature *s; git_oid__fromstr(&oid, "a65fedf39aefe402d3bb6e24df4d4f5fe4547750", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, _repo, &oid)); git_oid__fromstr(&oid, "944c0f6e4dfa41595e6eb3ceecdb14f50fe18162", GIT_OID_SHA1); cl_git_pass(git_tree_lookup(&tree, _repo, &oid)); cl_git_pass(git_signature_now(&s, "alice", "[email protected]")); cl_git_pass(git_reference_name_to_id(&original_oid, _repo, "HEAD")); cl_git_fail(git_commit_create(&oid, _repo, "HEAD", s, s, NULL, "initial commit", tree, 0, NULL)); cl_git_pass(git_reference_name_to_id(&oid, _repo, "HEAD")); cl_assert_equal_oid(&oid, &original_oid); git_tree_free(tree); git_commit_free(commit); git_signature_free(s); } static void assert_commit_summary(const char *expected, const char *given) { git_commit *dummy; cl_assert(dummy = git__calloc(1, sizeof(struct git_commit))); dummy->raw_message = git__strdup(given); cl_assert_equal_s(expected, git_commit_summary(dummy)); git_commit__free(dummy); } static void assert_commit_body(const char *expected, const char *given) { git_commit *dummy; cl_assert(dummy = git__calloc(1, sizeof(struct git_commit))); dummy->raw_message = git__strdup(given); cl_assert_equal_s(expected, git_commit_body(dummy)); git_commit__free(dummy); } void test_commit_commit__summary(void) { assert_commit_summary("One-liner with no trailing newline", "One-liner with no trailing newline"); assert_commit_summary("One-liner with trailing newline", "One-liner with trailing newline\n"); assert_commit_summary("One-liner with trailing newline and space", "One-liner with trailing newline and space\n "); assert_commit_summary("Trimmed leading&trailing newlines", "\n\nTrimmed leading&trailing newlines\n\n"); assert_commit_summary("First paragraph only", "\nFirst paragraph only\n\n(There are more!)"); assert_commit_summary("First paragraph only with space in the next line", "\nFirst paragraph only with space in the next line\n \n(There are more!)"); assert_commit_summary("First paragraph only with spaces in the next line", "\nFirst paragraph only with spaces in the next line\n \n(There are more!)"); assert_commit_summary("First paragraph with unwrapped trailing\tlines", "\nFirst paragraph\nwith unwrapped\ntrailing\tlines\n\n(Yes, unwrapped!)"); assert_commit_summary("\tLeading tabs", "\tLeading\n\ttabs\n\nare preserved"); /* tabs around newlines are collapsed down to a single space */ assert_commit_summary(" Leading Spaces", " Leading\n Spaces\n\nare preserved"); /* spaces around newlines are collapsed down to a single space */ assert_commit_summary("Trailing tabs\tare removed", "Trailing tabs\tare removed\t\t"); assert_commit_summary("Trailing spaces are removed", "Trailing spaces are removed "); assert_commit_summary("Trailing tabs", "Trailing tabs\t\n\nare removed"); assert_commit_summary("Trailing spaces", "Trailing spaces \n\nare removed"); assert_commit_summary("Newlines are replaced by spaces", "Newlines\nare\nreplaced by spaces\n"); assert_commit_summary(" Spaces after newlines are collapsed", "\n Spaces after newlines\n are\n collapsed\n "); /* newlines at the very beginning are ignored and not collapsed */ assert_commit_summary(" Spaces before newlines are collapsed", " \nSpaces before newlines \nare \ncollapsed \n"); assert_commit_summary(" Spaces around newlines are collapsed", " \n Spaces around newlines \n are \n collapsed \n "); assert_commit_summary(" Trailing newlines are" , " \n Trailing newlines \n are \n\n collapsed \n "); assert_commit_summary(" Trailing spaces are stripped", " \n Trailing spaces \n are stripped \n\n \n \t "); assert_commit_summary("", ""); assert_commit_summary("", " "); assert_commit_summary("", "\n"); assert_commit_summary("", "\n \n"); } void test_commit_commit__body(void) { assert_commit_body(NULL, "One-liner with no trailing newline"); assert_commit_body(NULL, "One-liner with trailing newline\n"); assert_commit_body(NULL, "\n\nTrimmed leading&trailing newlines\n\n"); assert_commit_body("(There are more!)", "\nFirst paragraph only\n\n(There are more!)"); assert_commit_body("(Yes, unwrapped!)", "\nFirst paragraph\nwith unwrapped\ntrailing\tlines\n\n(Yes, unwrapped!)"); assert_commit_body("are preserved", "\tLeading\n\ttabs\n\nare preserved"); /* tabs around newlines are collapsed down to a single space */ assert_commit_body("are preserved", " Leading\n Spaces\n\nare preserved"); /* spaces around newlines are collapsed down to a single space */ assert_commit_body(NULL, "Trailing tabs\tare removed\t\t"); assert_commit_body(NULL, "Trailing spaces are removed "); assert_commit_body("are removed", "Trailing tabs\t\n\nare removed"); assert_commit_body("are removed", "Trailing spaces \n\nare removed"); assert_commit_body(NULL,"Newlines\nare\nreplaced by spaces\n"); assert_commit_body(NULL , "\n Spaces after newlines\n are\n collapsed\n "); /* newlines at the very beginning are ignored and not collapsed */ assert_commit_body(NULL , " \nSpaces before newlines \nare \ncollapsed \n"); assert_commit_body(NULL , " \n Spaces around newlines \n are \n collapsed \n "); assert_commit_body("collapsed" , " \n Trailing newlines \n are \n\n collapsed \n "); assert_commit_body(NULL, " \n Trailing spaces \n are stripped \n\n \n \t "); assert_commit_body(NULL , ""); assert_commit_body(NULL , " "); assert_commit_body(NULL , "\n"); assert_commit_body(NULL , "\n \n"); }
libgit2-main
tests/libgit2/commit/commit.c
#include "clar_libgit2.h" #include "signature.h" static int try_build_signature(const char *name, const char *email, git_time_t time, int offset) { git_signature *sign; int error = 0; if ((error = git_signature_new(&sign, name, email, time, offset)) < 0) return error; git_signature_free((git_signature *)sign); return error; } static void assert_name_and_email( const char *expected_name, const char *expected_email, const char *name, const char *email) { git_signature *sign; cl_git_pass(git_signature_new(&sign, name, email, 1234567890, 60)); cl_assert_equal_s(expected_name, sign->name); cl_assert_equal_s(expected_email, sign->email); git_signature_free(sign); } void test_commit_signature__leading_and_trailing_spaces_are_trimmed(void) { assert_name_and_email("nulltoken", "[email protected]", " nulltoken ", " [email protected] "); assert_name_and_email("nulltoken", "[email protected]", " nulltoken ", " [email protected] \n"); assert_name_and_email("nulltoken", "[email protected]", " \t nulltoken \n", " \n [email protected] \n"); } void test_commit_signature__leading_and_trailing_crud_is_trimmed(void) { assert_name_and_email("nulltoken", "[email protected]", "\"nulltoken\"", "\"[email protected]\""); assert_name_and_email("nulltoken w", "[email protected]", "nulltoken w.", "[email protected]"); assert_name_and_email("nulltoken \xe2\x98\xba", "[email protected]", "nulltoken \xe2\x98\xba", "[email protected]"); } void test_commit_signature__timezone_does_not_read_oob(void) { const char *header = "A <[email protected]> 1461698487 +1234", *header_end; git_signature *sig; /* Let the buffer end midway between the timezone offeset's "+12" and "34" */ header_end = header + strlen(header) - 2; sig = git__calloc(1, sizeof(git_signature)); cl_assert(sig); cl_git_pass(git_signature__parse(sig, &header, header_end, NULL, '\0')); cl_assert_equal_s(sig->name, "A"); cl_assert_equal_s(sig->email, "[email protected]"); cl_assert_equal_i(sig->when.time, 1461698487); cl_assert_equal_i(sig->when.offset, 12); git_signature_free(sig); } void test_commit_signature__angle_brackets_in_names_are_not_supported(void) { cl_git_fail(try_build_signature("<Phil Haack", "phil@haack", 1234567890, 60)); cl_git_fail(try_build_signature("Phil>Haack", "phil@haack", 1234567890, 60)); cl_git_fail(try_build_signature("<Phil Haack>", "phil@haack", 1234567890, 60)); } void test_commit_signature__angle_brackets_in_email_are_not_supported(void) { cl_git_fail(try_build_signature("Phil Haack", ">phil@haack", 1234567890, 60)); cl_git_fail(try_build_signature("Phil Haack", "phil@>haack", 1234567890, 60)); cl_git_fail(try_build_signature("Phil Haack", "<phil@haack>", 1234567890, 60)); } void test_commit_signature__create_empties(void) { /* can not create a signature with empty name or email */ cl_git_pass(try_build_signature("nulltoken", "[email protected]", 1234567890, 60)); cl_git_fail(try_build_signature("", "[email protected]", 1234567890, 60)); cl_git_fail(try_build_signature(" ", "[email protected]", 1234567890, 60)); cl_git_fail(try_build_signature("nulltoken", "", 1234567890, 60)); cl_git_fail(try_build_signature("nulltoken", " ", 1234567890, 60)); } void test_commit_signature__create_one_char(void) { /* creating a one character signature */ assert_name_and_email("x", "[email protected]", "x", "[email protected]"); } void test_commit_signature__create_two_char(void) { /* creating a two character signature */ assert_name_and_email("xx", "[email protected]", "xx", "[email protected]"); } void test_commit_signature__create_zero_char(void) { /* creating a zero character signature */ git_signature *sign; cl_git_fail(git_signature_new(&sign, "", "[email protected]", 1234567890, 60)); cl_assert(sign == NULL); } void test_commit_signature__from_buf(void) { git_signature *sign; cl_git_pass(git_signature_from_buffer(&sign, "Test User <[email protected]> 1461698487 +0200")); cl_assert_equal_s("Test User", sign->name); cl_assert_equal_s("[email protected]", sign->email); cl_assert_equal_i(1461698487, sign->when.time); cl_assert_equal_i(120, sign->when.offset); git_signature_free(sign); } void test_commit_signature__from_buf_with_neg_zero_offset(void) { git_signature *sign; cl_git_pass(git_signature_from_buffer(&sign, "Test User <[email protected]> 1461698487 -0000")); cl_assert_equal_s("Test User", sign->name); cl_assert_equal_s("[email protected]", sign->email); cl_assert_equal_i(1461698487, sign->when.time); cl_assert_equal_i(0, sign->when.offset); cl_assert_equal_i('-', sign->when.sign); git_signature_free(sign); } void test_commit_signature__pos_and_neg_zero_offsets_dont_match(void) { git_signature *with_neg_zero; git_signature *with_pos_zero; cl_git_pass(git_signature_from_buffer(&with_neg_zero, "Test User <[email protected]> 1461698487 -0000")); cl_git_pass(git_signature_from_buffer(&with_pos_zero, "Test User <[email protected]> 1461698487 +0000")); cl_assert(!git_signature__equal(with_neg_zero, with_pos_zero)); git_signature_free((git_signature *)with_neg_zero); git_signature_free((git_signature *)with_pos_zero); }
libgit2-main
tests/libgit2/commit/signature.c
#include "clar_libgit2.h" #include <git2/types.h> #include "commit.h" #include "signature.h" /* Fixture setup */ static git_repository *g_repo; void test_commit_parse__initialize(void) { g_repo = cl_git_sandbox_init("testrepo"); } void test_commit_parse__cleanup(void) { cl_git_sandbox_cleanup(); } /* Header parsing */ typedef struct { const char *line; const char *header; } parse_test_case; static parse_test_case passing_header_cases[] = { { "parent 05452d6349abcd67aa396dfb28660d765d8b2a36\n", "parent " }, { "tree 05452d6349abcd67aa396dfb28660d765d8b2a36\n", "tree " }, { "random_heading 05452d6349abcd67aa396dfb28660d765d8b2a36\n", "random_heading " }, { "stuck_heading05452d6349abcd67aa396dfb28660d765d8b2a36\n", "stuck_heading" }, { "tree 5F4BEFFC0759261D015AA63A3A85613FF2F235DE\n", "tree " }, { "tree 1A669B8AB81B5EB7D9DB69562D34952A38A9B504\n", "tree " }, { "tree 5B20DCC6110FCC75D31C6CEDEBD7F43ECA65B503\n", "tree " }, { "tree 173E7BF00EA5C33447E99E6C1255954A13026BE4\n", "tree " }, { NULL, NULL } }; static parse_test_case failing_header_cases[] = { { "parent 05452d6349abcd67aa396dfb28660d765d8b2a36", "parent " }, { "05452d6349abcd67aa396dfb28660d765d8b2a36\n", "tree " }, { "parent05452d6349abcd67aa396dfb28660d765d8b2a6a\n", "parent " }, { "parent 05452d6349abcd67aa396dfb280d765d8b2a6\n", "parent " }, { "tree 05452d6349abcd67aa396dfb28660d765d8b2a36\n", "tree " }, { "parent 0545xd6349abcd67aa396dfb28660d765d8b2a36\n", "parent " }, { "parent 0545xd6349abcd67aa396dfb28660d765d8b2a36FF\n", "parent " }, { "", "tree " }, { "", "" }, { NULL, NULL } }; void test_commit_parse__header(void) { git_oid oid; parse_test_case *testcase; for (testcase = passing_header_cases; testcase->line != NULL; testcase++) { const char *line = testcase->line; const char *line_end = line + strlen(line); cl_git_pass(git_object__parse_oid_header(&oid, &line, line_end, testcase->header, GIT_OID_SHA1)); cl_assert(line == line_end); } for (testcase = failing_header_cases; testcase->line != NULL; testcase++) { const char *line = testcase->line; const char *line_end = line + strlen(line); cl_git_fail(git_object__parse_oid_header(&oid, &line, line_end, testcase->header, GIT_OID_SHA1)); } } /* Signature parsing */ typedef struct { const char *string; const char *header; const char *name; const char *email; git_time_t time; int offset; } passing_signature_test_case; passing_signature_test_case passing_signature_cases[] = { {"author Vicent Marti <[email protected]> 12345 \n", "author ", "Vicent Marti", "[email protected]", 12345, 0}, {"author Vicent Marti <> 12345 \n", "author ", "Vicent Marti", "", 12345, 0}, {"author Vicent Marti <[email protected]> 231301 +1020\n", "author ", "Vicent Marti", "[email protected]", 231301, 620}, {"author Vicent Marti with an outrageously long name which will probably overflow the buffer <[email protected]> 12345 \n", "author ", "Vicent Marti with an outrageously long name which will probably overflow the buffer", "[email protected]", 12345, 0}, {"author Vicent Marti <tanokuwithaveryveryverylongemailwhichwillprobablyvoverflowtheemailbuffer@gmail.com> 12345 \n", "author ", "Vicent Marti", "tanokuwithaveryveryverylongemailwhichwillprobablyvoverflowtheemailbuffer@gmail.com", 12345, 0}, {"committer Vicent Marti <[email protected]> 123456 +0000 \n", "committer ", "Vicent Marti", "[email protected]", 123456, 0}, {"committer Vicent Marti <[email protected]> 123456 +0100 \n", "committer ", "Vicent Marti", "[email protected]", 123456, 60}, {"committer Vicent Marti <[email protected]> 123456 -0100 \n", "committer ", "Vicent Marti", "[email protected]", 123456, -60}, /* Parse a signature without an author field */ {"committer <[email protected]> 123456 -0100 \n", "committer ", "", "[email protected]", 123456, -60}, /* Parse a signature without an author field */ {"committer <[email protected]> 123456 -0100 \n", "committer ", "", "[email protected]", 123456, -60}, /* Parse a signature with an empty author field */ {"committer <[email protected]> 123456 -0100 \n", "committer ", "", "[email protected]", 123456, -60}, /* Parse a signature with an empty email field */ {"committer Vicent Marti <> 123456 -0100 \n", "committer ", "Vicent Marti", "", 123456, -60}, /* Parse a signature with an empty email field */ {"committer Vicent Marti < > 123456 -0100 \n", "committer ", "Vicent Marti", "", 123456, -60}, /* Parse a signature with empty name and email */ {"committer <> 123456 -0100 \n", "committer ", "", "", 123456, -60}, /* Parse a signature with empty name and email */ {"committer <> 123456 -0100 \n", "committer ", "", "", 123456, -60}, /* Parse a signature with empty name and email */ {"committer < > 123456 -0100 \n", "committer ", "", "", 123456, -60}, /* Parse an obviously invalid signature */ {"committer foo<@bar> 123456 -0100 \n", "committer ", "foo", "@bar", 123456, -60}, /* Parse an obviously invalid signature */ {"committer foo<@bar> 123456 -0100 \n", "committer ", "foo", "@bar", 123456, -60}, /* Parse an obviously invalid signature */ {"committer <>\n", "committer ", "", "", 0, 0}, {"committer Vicent Marti <[email protected]> 123456 -1500 \n", "committer ", "Vicent Marti", "[email protected]", 123456, 0}, {"committer Vicent Marti <[email protected]> 123456 +0163 \n", "committer ", "Vicent Marti", "[email protected]", 123456, 0}, {"author Vicent Marti <[email protected]>\n", "author ", "Vicent Marti", "[email protected]", 0, 0}, /* a variety of dates */ {"author Vicent Marti <[email protected]> 0 \n", "author ", "Vicent Marti", "[email protected]", 0, 0}, {"author Vicent Marti <[email protected]> 1234567890 \n", "author ", "Vicent Marti", "[email protected]", 1234567890, 0}, {"author Vicent Marti <[email protected]> 2147483647 \n", "author ", "Vicent Marti", "[email protected]", 0x7fffffff, 0}, {"author Vicent Marti <[email protected]> 4294967295 \n", "author ", "Vicent Marti", "[email protected]", 0xffffffff, 0}, {"author Vicent Marti <[email protected]> 4294967296 \n", "author ", "Vicent Marti", "[email protected]", 4294967296, 0}, {"author Vicent Marti <[email protected]> 8589934592 \n", "author ", "Vicent Marti", "[email protected]", 8589934592, 0}, {NULL,NULL,NULL,NULL,0,0} }; typedef struct { const char *string; const char *header; } failing_signature_test_case; failing_signature_test_case failing_signature_cases[] = { {"committer Vicent Marti [email protected]> 123456 -0100 \n", "committer "}, {"author Vicent Marti <[email protected]> 12345 \n", "author "}, {"author Vicent Marti <[email protected]> 12345 \n", "committer "}, {"author Vicent Marti 12345 \n", "author "}, {"author Vicent Marti <broken@email 12345 \n", "author "}, {"committer Vicent Marti ><\n", "committer "}, {"author ", "author "}, {NULL, NULL,} }; void test_commit_parse__signature(void) { passing_signature_test_case *passcase; failing_signature_test_case *failcase; for (passcase = passing_signature_cases; passcase->string != NULL; passcase++) { const char *str = passcase->string; size_t len = strlen(passcase->string); struct git_signature person = {0}; cl_git_pass(git_signature__parse(&person, &str, str + len, passcase->header, '\n')); cl_assert_equal_s(passcase->name, person.name); cl_assert_equal_s(passcase->email, person.email); cl_assert_equal_i((int)passcase->time, (int)person.when.time); cl_assert_equal_i(passcase->offset, person.when.offset); git__free(person.name); git__free(person.email); } for (failcase = failing_signature_cases; failcase->string != NULL; failcase++) { const char *str = failcase->string; size_t len = strlen(failcase->string); git_signature person = {0}; cl_git_fail(git_signature__parse(&person, &str, str + len, failcase->header, '\n')); git__free(person.name); git__free(person.email); } } static char *failing_commit_cases[] = { /* empty commit */ "", /* random garbage */ "asd97sa9du902e9a0jdsuusad09as9du098709aweu8987sd\n", /* broken endlines 1 */ "tree f6c0dad3c7b3481caa9d73db21f91964894a945b\r\n\ parent 05452d6349abcd67aa396dfb28660d765d8b2a36\r\n\ author Vicent Marti <[email protected]> 1273848544 +0200\r\n\ committer Vicent Marti <[email protected]> 1273848544 +0200\r\n\ \r\n\ a test commit with broken endlines\r\n", /* broken endlines 2 */ "tree f6c0dad3c7b3481caa9d73db21f91964894a945b\ parent 05452d6349abcd67aa396dfb28660d765d8b2a36\ author Vicent Marti <[email protected]> 1273848544 +0200\ committer Vicent Marti <[email protected]> 1273848544 +0200\ \ another test commit with broken endlines", /* starting endlines */ "\ntree f6c0dad3c7b3481caa9d73db21f91964894a945b\n\ parent 05452d6349abcd67aa396dfb28660d765d8b2a36\n\ author Vicent Marti <[email protected]> 1273848544 +0200\n\ committer Vicent Marti <[email protected]> 1273848544 +0200\n\ \n\ a test commit with a starting endline\n", /* corrupted commit 1 */ "tree f6c0dad3c7b3481caa9d73db21f91964894a945b\n\ parent 05452d6349abcd67aa396df", /* corrupted commit 2 */ "tree f6c0dad3c7b3481caa9d73db21f91964894a945b\n\ parent ", /* corrupted commit 3 */ "tree f6c0dad3c7b3481caa9d73db21f91964894a945b\n\ parent ", /* corrupted commit 4 */ "tree f6c0dad3c7b3481caa9d73db21f91964894a945b\n\ par", }; static char *passing_commit_cases[] = { /* simple commit with no message */ "tree 1810dff58d8a660512d4832e740f692884338ccd\n\ author Vicent Marti <[email protected]> 1273848544 +0200\n\ committer Vicent Marti <[email protected]> 1273848544 +0200\n\ \n", /* simple commit, no parent */ "tree 1810dff58d8a660512d4832e740f692884338ccd\n\ author Vicent Marti <[email protected]> 1273848544 +0200\n\ committer Vicent Marti <[email protected]> 1273848544 +0200\n\ \n\ a simple commit which works\n", /* simple commit, no parent, no newline in message */ "tree 1810dff58d8a660512d4832e740f692884338ccd\n\ author Vicent Marti <[email protected]> 1273848544 +0200\n\ committer Vicent Marti <[email protected]> 1273848544 +0200\n\ \n\ a simple commit which works", /* simple commit, 1 parent */ "tree 1810dff58d8a660512d4832e740f692884338ccd\n\ parent e90810b8df3e80c413d903f631643c716887138d\n\ author Vicent Marti <[email protected]> 1273848544 +0200\n\ committer Vicent Marti <[email protected]> 1273848544 +0200\n\ \n\ a simple commit which works\n", /* simple commit with GPG signature */ "tree 6b79e22d69bf46e289df0345a14ca059dfc9bdf6\n\ parent 34734e478d6cf50c27c9d69026d93974d052c454\n\ author Ben Burkert <[email protected]> 1358451456 -0800\n\ committer Ben Burkert <[email protected]> 1358451456 -0800\n\ gpgsig -----BEGIN PGP SIGNATURE-----\n\ Version: GnuPG v1.4.12 (Darwin)\n\ \n\ iQIcBAABAgAGBQJQ+FMIAAoJEH+LfPdZDSs1e3EQAJMjhqjWF+WkGLHju7pTw2al\n\ o6IoMAhv0Z/LHlWhzBd9e7JeCnanRt12bAU7yvYp9+Z+z+dbwqLwDoFp8LVuigl8\n\ JGLcnwiUW3rSvhjdCp9irdb4+bhKUnKUzSdsR2CK4/hC0N2i/HOvMYX+BRsvqweq\n\ AsAkA6dAWh+gAfedrBUkCTGhlNYoetjdakWqlGL1TiKAefEZrtA1TpPkGn92vbLq\n\ SphFRUY9hVn1ZBWrT3hEpvAIcZag3rTOiRVT1X1flj8B2vGCEr3RrcwOIZikpdaW\n\ who/X3xh/DGbI2RbuxmmJpxxP/8dsVchRJJzBwG+yhwU/iN3MlV2c5D69tls/Dok\n\ 6VbyU4lm/ae0y3yR83D9dUlkycOnmmlBAHKIZ9qUts9X7mWJf0+yy2QxJVpjaTGG\n\ cmnQKKPeNIhGJk2ENnnnzjEve7L7YJQF6itbx5VCOcsGh3Ocb3YR7DMdWjt7f8pu\n\ c6j+q1rP7EpE2afUN/geSlp5i3x8aXZPDj67jImbVCE/Q1X9voCtyzGJH7MXR0N9\n\ ZpRF8yzveRfMH8bwAJjSOGAFF5XkcR/RNY95o+J+QcgBLdX48h+ZdNmUf6jqlu3J\n\ 7KmTXXQcOVpN6dD3CmRFsbjq+x6RHwa8u1iGn+oIkX908r97ckfB/kHKH7ZdXIJc\n\ cpxtDQQMGYFpXK/71stq\n\ =ozeK\n\ -----END PGP SIGNATURE-----\n\ \n\ a simple commit which works\n", /* some tools create two author entries */ "tree 1810dff58d8a660512d4832e740f692884338ccd\n\ author Vicent Marti <[email protected]> 1273848544 +0200\n\ author Helpful Coworker <helpful@coworker> 1273848544 +0200\n\ committer Vicent Marti <[email protected]> 1273848544 +0200\n\ \n\ a simple commit which works", }; static int parse_commit(git_commit **out, const char *buffer) { git_commit *commit; git_odb_object fake_odb_object; int error; commit = (git_commit*)git__malloc(sizeof(git_commit)); memset(commit, 0x0, sizeof(git_commit)); commit->object.repo = g_repo; memset(&fake_odb_object, 0x0, sizeof(git_odb_object)); fake_odb_object.buffer = (char *)buffer; fake_odb_object.cached.size = strlen(fake_odb_object.buffer); error = git_commit__parse(commit, &fake_odb_object); *out = commit; return error; } void test_commit_parse__entire_commit(void) { const int failing_commit_count = ARRAY_SIZE(failing_commit_cases); const int passing_commit_count = ARRAY_SIZE(passing_commit_cases); int i; git_commit *commit; for (i = 0; i < failing_commit_count; ++i) { cl_git_fail(parse_commit(&commit, failing_commit_cases[i])); git_commit__free(commit); } for (i = 0; i < passing_commit_count; ++i) { cl_git_pass(parse_commit(&commit, passing_commit_cases[i])); if (!i) cl_assert_equal_s("", git_commit_message(commit)); else cl_assert(git__prefixcmp( git_commit_message(commit), "a simple commit which works") == 0); git_commit__free(commit); } } /* query the details on a parsed commit */ void test_commit_parse__details0(void) { static const char *commit_ids[] = { "a4a7dce85cf63874e984719f4fdd239f5145052f", /* 0 */ "9fd738e8f7967c078dceed8190330fc8648ee56a", /* 1 */ "4a202b346bb0fb0db7eff3cffeb3c70babbd2045", /* 2 */ "c47800c7266a2be04c571c04d5a6614691ea99bd", /* 3 */ "8496071c1b46c854b31185ea97743be6a8774479", /* 4 */ "5b5b025afb0b4c913b4c338a42934a3863bf3644", /* 5 */ "a65fedf39aefe402d3bb6e24df4d4f5fe4547750", /* 6 */ }; const size_t commit_count = sizeof(commit_ids) / sizeof(const char *); unsigned int i; for (i = 0; i < commit_count; ++i) { git_oid id; git_commit *commit; const git_signature *author, *committer; const char *message; git_time_t commit_time; unsigned int parents, p; git_commit *parent = NULL, *old_parent = NULL; git_oid__fromstr(&id, commit_ids[i], GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, g_repo, &id)); message = git_commit_message(commit); author = git_commit_author(commit); committer = git_commit_committer(commit); commit_time = git_commit_time(commit); parents = git_commit_parentcount(commit); cl_assert_equal_s("Scott Chacon", author->name); cl_assert_equal_s("[email protected]", author->email); cl_assert_equal_s("Scott Chacon", committer->name); cl_assert_equal_s("[email protected]", committer->email); cl_assert(message != NULL); cl_assert(commit_time > 0); cl_assert(parents <= 2); for (p = 0;p < parents;p++) { if (old_parent != NULL) git_commit_free(old_parent); old_parent = parent; cl_git_pass(git_commit_parent(&parent, commit, p)); cl_assert(parent != NULL); cl_assert(git_commit_author(parent) != NULL); /* is it really a commit? */ } git_commit_free(old_parent); git_commit_free(parent); cl_git_fail(git_commit_parent(&parent, commit, parents)); git_commit_free(commit); } } void test_commit_parse__leading_lf(void) { git_commit *commit; const char *buffer = "tree 1810dff58d8a660512d4832e740f692884338ccd\n\ parent e90810b8df3e80c413d903f631643c716887138d\n\ author Vicent Marti <[email protected]> 1273848544 +0200\n\ committer Vicent Marti <[email protected]> 1273848544 +0200\n\ \n\ \n\ \n\ This commit has a few LF at the start of the commit message"; const char *message = "This commit has a few LF at the start of the commit message"; const char *raw_message = "\n\ \n\ This commit has a few LF at the start of the commit message"; cl_git_pass(parse_commit(&commit, buffer)); cl_assert_equal_s(message, git_commit_message(commit)); cl_assert_equal_s(raw_message, git_commit_message_raw(commit)); git_commit__free(commit); } void test_commit_parse__only_lf(void) { git_commit *commit; const char *buffer = "tree 1810dff58d8a660512d4832e740f692884338ccd\n\ parent e90810b8df3e80c413d903f631643c716887138d\n\ author Vicent Marti <[email protected]> 1273848544 +0200\n\ committer Vicent Marti <[email protected]> 1273848544 +0200\n\ \n\ \n\ \n"; const char *message = ""; const char *raw_message = "\n\n"; cl_git_pass(parse_commit(&commit, buffer)); cl_assert_equal_s(message, git_commit_message(commit)); cl_assert_equal_s(raw_message, git_commit_message_raw(commit)); git_commit__free(commit); } void test_commit_parse__arbitrary_field(void) { git_commit *commit; git_buf buf = GIT_BUF_INIT; const char *gpgsig = "-----BEGIN PGP SIGNATURE-----\n\ Version: GnuPG v1.4.12 (Darwin)\n\ \n\ iQIcBAABAgAGBQJQ+FMIAAoJEH+LfPdZDSs1e3EQAJMjhqjWF+WkGLHju7pTw2al\n\ o6IoMAhv0Z/LHlWhzBd9e7JeCnanRt12bAU7yvYp9+Z+z+dbwqLwDoFp8LVuigl8\n\ JGLcnwiUW3rSvhjdCp9irdb4+bhKUnKUzSdsR2CK4/hC0N2i/HOvMYX+BRsvqweq\n\ AsAkA6dAWh+gAfedrBUkCTGhlNYoetjdakWqlGL1TiKAefEZrtA1TpPkGn92vbLq\n\ SphFRUY9hVn1ZBWrT3hEpvAIcZag3rTOiRVT1X1flj8B2vGCEr3RrcwOIZikpdaW\n\ who/X3xh/DGbI2RbuxmmJpxxP/8dsVchRJJzBwG+yhwU/iN3MlV2c5D69tls/Dok\n\ 6VbyU4lm/ae0y3yR83D9dUlkycOnmmlBAHKIZ9qUts9X7mWJf0+yy2QxJVpjaTGG\n\ cmnQKKPeNIhGJk2ENnnnzjEve7L7YJQF6itbx5VCOcsGh3Ocb3YR7DMdWjt7f8pu\n\ c6j+q1rP7EpE2afUN/geSlp5i3x8aXZPDj67jImbVCE/Q1X9voCtyzGJH7MXR0N9\n\ ZpRF8yzveRfMH8bwAJjSOGAFF5XkcR/RNY95o+J+QcgBLdX48h+ZdNmUf6jqlu3J\n\ 7KmTXXQcOVpN6dD3CmRFsbjq+x6RHwa8u1iGn+oIkX908r97ckfB/kHKH7ZdXIJc\n\ cpxtDQQMGYFpXK/71stq\n\ =ozeK\n\ -----END PGP SIGNATURE-----"; cl_git_pass(parse_commit(&commit, passing_commit_cases[4])); cl_git_pass(git_commit_header_field(&buf, commit, "tree")); cl_assert_equal_s("6b79e22d69bf46e289df0345a14ca059dfc9bdf6", buf.ptr); git_buf_dispose(&buf); cl_git_pass(git_commit_header_field(&buf, commit, "parent")); cl_assert_equal_s("34734e478d6cf50c27c9d69026d93974d052c454", buf.ptr); git_buf_dispose(&buf); cl_git_pass(git_commit_header_field(&buf, commit, "gpgsig")); cl_assert_equal_s(gpgsig, buf.ptr); git_buf_dispose(&buf); cl_git_fail_with(GIT_ENOTFOUND, git_commit_header_field(&buf, commit, "awesomeness")); cl_git_fail_with(GIT_ENOTFOUND, git_commit_header_field(&buf, commit, "par")); git_commit__free(commit); cl_git_pass(parse_commit(&commit, passing_commit_cases[0])); cl_git_pass(git_commit_header_field(&buf, commit, "committer")); cl_assert_equal_s("Vicent Marti <[email protected]> 1273848544 +0200", buf.ptr); git_buf_dispose(&buf); git_commit__free(commit); } void test_commit_parse__extract_signature(void) { git_odb *odb; git_oid commit_id; git_buf signature = GIT_BUF_INIT, signed_data = GIT_BUF_INIT; const char *gpgsig = "-----BEGIN PGP SIGNATURE-----\n\ Version: GnuPG v1.4.12 (Darwin)\n\ \n\ iQIcBAABAgAGBQJQ+FMIAAoJEH+LfPdZDSs1e3EQAJMjhqjWF+WkGLHju7pTw2al\n\ o6IoMAhv0Z/LHlWhzBd9e7JeCnanRt12bAU7yvYp9+Z+z+dbwqLwDoFp8LVuigl8\n\ JGLcnwiUW3rSvhjdCp9irdb4+bhKUnKUzSdsR2CK4/hC0N2i/HOvMYX+BRsvqweq\n\ AsAkA6dAWh+gAfedrBUkCTGhlNYoetjdakWqlGL1TiKAefEZrtA1TpPkGn92vbLq\n\ SphFRUY9hVn1ZBWrT3hEpvAIcZag3rTOiRVT1X1flj8B2vGCEr3RrcwOIZikpdaW\n\ who/X3xh/DGbI2RbuxmmJpxxP/8dsVchRJJzBwG+yhwU/iN3MlV2c5D69tls/Dok\n\ 6VbyU4lm/ae0y3yR83D9dUlkycOnmmlBAHKIZ9qUts9X7mWJf0+yy2QxJVpjaTGG\n\ cmnQKKPeNIhGJk2ENnnnzjEve7L7YJQF6itbx5VCOcsGh3Ocb3YR7DMdWjt7f8pu\n\ c6j+q1rP7EpE2afUN/geSlp5i3x8aXZPDj67jImbVCE/Q1X9voCtyzGJH7MXR0N9\n\ ZpRF8yzveRfMH8bwAJjSOGAFF5XkcR/RNY95o+J+QcgBLdX48h+ZdNmUf6jqlu3J\n\ 7KmTXXQcOVpN6dD3CmRFsbjq+x6RHwa8u1iGn+oIkX908r97ckfB/kHKH7ZdXIJc\n\ cpxtDQQMGYFpXK/71stq\n\ =ozeK\n\ -----END PGP SIGNATURE-----"; const char *data = "tree 6b79e22d69bf46e289df0345a14ca059dfc9bdf6\n\ parent 34734e478d6cf50c27c9d69026d93974d052c454\n\ author Ben Burkert <[email protected]> 1358451456 -0800\n\ committer Ben Burkert <[email protected]> 1358451456 -0800\n\ \n\ a simple commit which works\n"; const char *oneline_signature = "tree 51832e6397b30309c8bcad9c55fa6ae67778f378\n\ parent a1b6decaaac768b5e01e1b5dbf5b2cc081bed1eb\n\ author Some User <[email protected]> 1454537944 -0700\n\ committer Some User <[email protected]> 1454537944 -0700\n\ gpgsig bad\n\ \n\ corrupt signature\n"; const char *oneline_data = "tree 51832e6397b30309c8bcad9c55fa6ae67778f378\n\ parent a1b6decaaac768b5e01e1b5dbf5b2cc081bed1eb\n\ author Some User <[email protected]> 1454537944 -0700\n\ committer Some User <[email protected]> 1454537944 -0700\n\ \n\ corrupt signature\n"; cl_git_pass(git_repository_odb__weakptr(&odb, g_repo)); cl_git_pass(git_odb_write(&commit_id, odb, passing_commit_cases[4], strlen(passing_commit_cases[4]), GIT_OBJECT_COMMIT)); cl_git_pass(git_commit_extract_signature(&signature, &signed_data, g_repo, &commit_id, NULL)); cl_assert_equal_s(gpgsig, signature.ptr); cl_assert_equal_s(data, signed_data.ptr); git_buf_dispose(&signature); git_buf_dispose(&signed_data); cl_git_pass(git_commit_extract_signature(&signature, &signed_data, g_repo, &commit_id, "gpgsig")); cl_assert_equal_s(gpgsig, signature.ptr); cl_assert_equal_s(data, signed_data.ptr); git_buf_dispose(&signature); git_buf_dispose(&signed_data); /* Try to parse a tree */ cl_git_pass(git_oid__fromstr(&commit_id, "45dd856fdd4d89b884c340ba0e047752d9b085d6", GIT_OID_SHA1)); cl_git_fail_with(GIT_ENOTFOUND, git_commit_extract_signature(&signature, &signed_data, g_repo, &commit_id, NULL)); cl_assert_equal_i(GIT_ERROR_INVALID, git_error_last()->klass); /* Try to parse an unsigned commit */ cl_git_pass(git_odb_write(&commit_id, odb, passing_commit_cases[1], strlen(passing_commit_cases[1]), GIT_OBJECT_COMMIT)); cl_git_fail_with(GIT_ENOTFOUND, git_commit_extract_signature(&signature, &signed_data, g_repo, &commit_id, NULL)); cl_assert_equal_i(GIT_ERROR_OBJECT, git_error_last()->klass); /* Parse the commit with a single-line signature */ cl_git_pass(git_odb_write(&commit_id, odb, oneline_signature, strlen(oneline_signature), GIT_OBJECT_COMMIT)); cl_git_pass(git_commit_extract_signature(&signature, &signed_data, g_repo, &commit_id, NULL)); cl_assert_equal_s("bad", signature.ptr); cl_assert_equal_s(oneline_data, signed_data.ptr); git_buf_dispose(&signature); git_buf_dispose(&signed_data); }
libgit2-main
tests/libgit2/commit/parse.c
#include "clar_libgit2.h" #include "git2/sys/commit.h" static const char *committer_name = "Vicent Marti"; static const char *committer_email = "[email protected]"; static const char *commit_message = "This commit has been created in memory\n\ This is a commit created in memory and it will be written back to disk\n"; static const char *tree_id_str = "1810dff58d8a660512d4832e740f692884338ccd"; static const char *parent_id_str = "8496071c1b46c854b31185ea97743be6a8774479"; static const char *root_commit_message = "This is a root commit\n\ This is a root commit and should be the only one in this branch\n"; static const char *root_reflog_message = "commit (initial): This is a root commit \ This is a root commit and should be the only one in this branch"; static char *head_old; static git_reference *head, *branch; static git_commit *commit; /* Fixture setup */ static git_repository *g_repo; void test_commit_write__initialize(void) { g_repo = cl_git_sandbox_init("testrepo"); } void test_commit_write__cleanup(void) { git_reference_free(head); head = NULL; git_reference_free(branch); branch = NULL; git_commit_free(commit); commit = NULL; git__free(head_old); head_old = NULL; cl_git_sandbox_cleanup(); cl_git_pass(git_libgit2_opts(GIT_OPT_ENABLE_STRICT_OBJECT_CREATION, 1)); } /* write a new commit object from memory to disk */ void test_commit_write__from_memory(void) { git_oid tree_id, parent_id, commit_id; git_signature *author, *committer; const git_signature *author1, *committer1; git_commit *parent; git_tree *tree; git_oid__fromstr(&tree_id, tree_id_str, GIT_OID_SHA1); cl_git_pass(git_tree_lookup(&tree, g_repo, &tree_id)); git_oid__fromstr(&parent_id, parent_id_str, GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&parent, g_repo, &parent_id)); /* create signatures */ cl_git_pass(git_signature_new(&committer, committer_name, committer_email, 123456789, 60)); cl_git_pass(git_signature_new(&author, committer_name, committer_email, 987654321, 90)); cl_git_pass(git_commit_create_v( &commit_id, /* out id */ g_repo, NULL, /* do not update the HEAD */ author, committer, NULL, commit_message, tree, 1, parent)); git_object_free((git_object *)parent); git_object_free((git_object *)tree); git_signature_free(committer); git_signature_free(author); cl_git_pass(git_commit_lookup(&commit, g_repo, &commit_id)); /* Check attributes were set correctly */ author1 = git_commit_author(commit); cl_assert(author1 != NULL); cl_assert_equal_s(committer_name, author1->name); cl_assert_equal_s(committer_email, author1->email); cl_assert(author1->when.time == 987654321); cl_assert(author1->when.offset == 90); committer1 = git_commit_committer(commit); cl_assert(committer1 != NULL); cl_assert_equal_s(committer_name, committer1->name); cl_assert_equal_s(committer_email, committer1->email); cl_assert(committer1->when.time == 123456789); cl_assert(committer1->when.offset == 60); cl_assert_equal_s(commit_message, git_commit_message(commit)); } void test_commit_write__into_buf(void) { git_oid tree_id; git_signature *author, *committer; git_tree *tree; git_commit *parent; git_oid parent_id; git_buf commit = GIT_BUF_INIT; git_oid__fromstr(&tree_id, tree_id_str, GIT_OID_SHA1); cl_git_pass(git_tree_lookup(&tree, g_repo, &tree_id)); /* create signatures */ cl_git_pass(git_signature_new(&committer, committer_name, committer_email, 123456789, 60)); cl_git_pass(git_signature_new(&author, committer_name, committer_email, 987654321, 90)); git_oid__fromstr(&parent_id, parent_id_str, GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&parent, g_repo, &parent_id)); cl_git_pass(git_commit_create_buffer(&commit, g_repo, author, committer, NULL, root_commit_message, tree, 1, (const git_commit **) &parent)); cl_assert_equal_s(commit.ptr, "tree 1810dff58d8a660512d4832e740f692884338ccd\n\ parent 8496071c1b46c854b31185ea97743be6a8774479\n\ author Vicent Marti <[email protected]> 987654321 +0130\n\ committer Vicent Marti <[email protected]> 123456789 +0100\n\ \n\ This is a root commit\n\ This is a root commit and should be the only one in this branch\n\ "); git_buf_dispose(&commit); git_tree_free(tree); git_commit_free(parent); git_signature_free(author); git_signature_free(committer); } /* create a root commit */ void test_commit_write__root(void) { git_oid tree_id, commit_id; const git_oid *branch_oid; git_signature *author, *committer; const char *branch_name = "refs/heads/root-commit-branch"; git_tree *tree; git_reflog *log; const git_reflog_entry *entry; git_oid__fromstr(&tree_id, tree_id_str, GIT_OID_SHA1); cl_git_pass(git_tree_lookup(&tree, g_repo, &tree_id)); /* create signatures */ cl_git_pass(git_signature_new(&committer, committer_name, committer_email, 123456789, 60)); cl_git_pass(git_signature_new(&author, committer_name, committer_email, 987654321, 90)); /* First we need to update HEAD so it points to our non-existent branch */ cl_git_pass(git_reference_lookup(&head, g_repo, "HEAD")); cl_assert(git_reference_type(head) == GIT_REFERENCE_SYMBOLIC); head_old = git__strdup(git_reference_symbolic_target(head)); cl_assert(head_old != NULL); git_reference_free(head); cl_git_pass(git_reference_symbolic_create(&head, g_repo, "HEAD", branch_name, 1, NULL)); cl_git_pass(git_commit_create_v( &commit_id, /* out id */ g_repo, "HEAD", author, committer, NULL, root_commit_message, tree, 0)); git_object_free((git_object *)tree); git_signature_free(author); /* * The fact that creating a commit works has already been * tested. Here we just make sure it's our commit and that it was * written as a root commit. */ cl_git_pass(git_commit_lookup(&commit, g_repo, &commit_id)); cl_assert(git_commit_parentcount(commit) == 0); cl_git_pass(git_reference_lookup(&branch, g_repo, branch_name)); branch_oid = git_reference_target(branch); cl_assert_equal_oid(branch_oid, &commit_id); cl_assert_equal_s(root_commit_message, git_commit_message(commit)); cl_git_pass(git_reflog_read(&log, g_repo, branch_name)); cl_assert_equal_i(1, git_reflog_entrycount(log)); entry = git_reflog_entry_byindex(log, 0); cl_assert_equal_s(committer->email, git_reflog_entry_committer(entry)->email); cl_assert_equal_s(committer->name, git_reflog_entry_committer(entry)->name); cl_assert_equal_s(root_reflog_message, git_reflog_entry_message(entry)); git_signature_free(committer); git_reflog_free(log); } static int create_commit_from_ids( git_oid *result, const git_oid *tree_id, const git_oid *parent_id) { git_signature *author, *committer; const git_oid *parent_ids[1]; int ret; cl_git_pass(git_signature_new( &committer, committer_name, committer_email, 123456789, 60)); cl_git_pass(git_signature_new( &author, committer_name, committer_email, 987654321, 90)); parent_ids[0] = parent_id; ret = git_commit_create_from_ids( result, g_repo, NULL, author, committer, NULL, root_commit_message, tree_id, 1, parent_ids); git_signature_free(committer); git_signature_free(author); return ret; } void test_commit_write__can_write_invalid_objects(void) { git_oid expected_id, tree_id, parent_id, commit_id; cl_git_pass(git_libgit2_opts(GIT_OPT_ENABLE_STRICT_OBJECT_CREATION, 0)); /* this is a valid tree and parent */ git_oid__fromstr(&tree_id, tree_id_str, GIT_OID_SHA1); git_oid__fromstr(&parent_id, parent_id_str, GIT_OID_SHA1); git_oid__fromstr(&expected_id, "c8571bbec3a72c4bcad31648902e5a453f1adece", GIT_OID_SHA1); cl_git_pass(create_commit_from_ids(&commit_id, &tree_id, &parent_id)); cl_assert_equal_oid(&expected_id, &commit_id); /* this is a wholly invented tree id */ git_oid__fromstr(&tree_id, "1234567890123456789012345678901234567890", GIT_OID_SHA1); git_oid__fromstr(&parent_id, parent_id_str, GIT_OID_SHA1); git_oid__fromstr(&expected_id, "996008340b8e68d69bf3c28d7c57fb7ec3c8e202", GIT_OID_SHA1); cl_git_pass(create_commit_from_ids(&commit_id, &tree_id, &parent_id)); cl_assert_equal_oid(&expected_id, &commit_id); /* this is a wholly invented parent id */ git_oid__fromstr(&tree_id, tree_id_str, GIT_OID_SHA1); git_oid__fromstr(&parent_id, "1234567890123456789012345678901234567890", GIT_OID_SHA1); git_oid__fromstr(&expected_id, "d78f660cab89d9791ca6714b57978bf2a7e709fd", GIT_OID_SHA1); cl_git_pass(create_commit_from_ids(&commit_id, &tree_id, &parent_id)); cl_assert_equal_oid(&expected_id, &commit_id); /* these are legitimate objects, but of the wrong type */ git_oid__fromstr(&tree_id, parent_id_str, GIT_OID_SHA1); git_oid__fromstr(&parent_id, tree_id_str, GIT_OID_SHA1); git_oid__fromstr(&expected_id, "5d80c07414e3f18792949699dfcacadf7748f361", GIT_OID_SHA1); cl_git_pass(create_commit_from_ids(&commit_id, &tree_id, &parent_id)); cl_assert_equal_oid(&expected_id, &commit_id); } void test_commit_write__can_validate_objects(void) { git_oid tree_id, parent_id, commit_id; /* this is a valid tree and parent */ git_oid__fromstr(&tree_id, tree_id_str, GIT_OID_SHA1); git_oid__fromstr(&parent_id, parent_id_str, GIT_OID_SHA1); cl_git_pass(create_commit_from_ids(&commit_id, &tree_id, &parent_id)); /* this is a wholly invented tree id */ git_oid__fromstr(&tree_id, "1234567890123456789012345678901234567890", GIT_OID_SHA1); git_oid__fromstr(&parent_id, parent_id_str, GIT_OID_SHA1); cl_git_fail(create_commit_from_ids(&commit_id, &tree_id, &parent_id)); /* this is a wholly invented parent id */ git_oid__fromstr(&tree_id, tree_id_str, GIT_OID_SHA1); git_oid__fromstr(&parent_id, "1234567890123456789012345678901234567890", GIT_OID_SHA1); cl_git_fail(create_commit_from_ids(&commit_id, &tree_id, &parent_id)); /* these are legitimate objects, but of the wrong type */ git_oid__fromstr(&tree_id, parent_id_str, GIT_OID_SHA1); git_oid__fromstr(&parent_id, tree_id_str, GIT_OID_SHA1); cl_git_fail(create_commit_from_ids(&commit_id, &tree_id, &parent_id)); } void test_commit_write__attach_signature_checks_objects(void) { const char *sig = "magic word: pretty please"; const char *badtree = "tree 6b79e22d69bf46e289df0345a14ca059dfc9bdf6\n\ parent 34734e478d6cf50c27c9d69026d93974d052c454\n\ author Ben Burkert <[email protected]> 1358451456 -0800\n\ committer Ben Burkert <[email protected]> 1358451456 -0800\n\ \n\ a simple commit which does not work\n"; const char *badparent = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\ parent 34734e478d6cf50c27c9d69026d93974d052c454\n\ author Ben Burkert <[email protected]> 1358451456 -0800\n\ committer Ben Burkert <[email protected]> 1358451456 -0800\n\ \n\ a simple commit which does not work\n"; git_oid id; cl_git_fail_with(-1, git_commit_create_with_signature(&id, g_repo, badtree, sig, "magicsig")); cl_git_fail_with(-1, git_commit_create_with_signature(&id, g_repo, badparent, sig, "magicsig")); } void test_commit_write__attach_singleline_signature(void) { const char *sig = "magic word: pretty please"; const char *data = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\ parent 8496071c1b46c854b31185ea97743be6a8774479\n\ author Ben Burkert <[email protected]> 1358451456 -0800\n\ committer Ben Burkert <[email protected]> 1358451456 -0800\n\ \n\ a simple commit which works\n"; const char *complete = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\ parent 8496071c1b46c854b31185ea97743be6a8774479\n\ author Ben Burkert <[email protected]> 1358451456 -0800\n\ committer Ben Burkert <[email protected]> 1358451456 -0800\n\ magicsig magic word: pretty please\n\ \n\ a simple commit which works\n"; git_oid id; git_odb *odb; git_odb_object *obj; cl_git_pass(git_commit_create_with_signature(&id, g_repo, data, sig, "magicsig")); cl_git_pass(git_repository_odb(&odb, g_repo)); cl_git_pass(git_odb_read(&obj, odb, &id)); cl_assert_equal_s(complete, git_odb_object_data(obj)); git_odb_object_free(obj); git_odb_free(odb); } void test_commit_write__attach_multiline_signature(void) { const char *gpgsig = "-----BEGIN PGP SIGNATURE-----\n\ Version: GnuPG v1.4.12 (Darwin)\n\ \n\ iQIcBAABAgAGBQJQ+FMIAAoJEH+LfPdZDSs1e3EQAJMjhqjWF+WkGLHju7pTw2al\n\ o6IoMAhv0Z/LHlWhzBd9e7JeCnanRt12bAU7yvYp9+Z+z+dbwqLwDoFp8LVuigl8\n\ JGLcnwiUW3rSvhjdCp9irdb4+bhKUnKUzSdsR2CK4/hC0N2i/HOvMYX+BRsvqweq\n\ AsAkA6dAWh+gAfedrBUkCTGhlNYoetjdakWqlGL1TiKAefEZrtA1TpPkGn92vbLq\n\ SphFRUY9hVn1ZBWrT3hEpvAIcZag3rTOiRVT1X1flj8B2vGCEr3RrcwOIZikpdaW\n\ who/X3xh/DGbI2RbuxmmJpxxP/8dsVchRJJzBwG+yhwU/iN3MlV2c5D69tls/Dok\n\ 6VbyU4lm/ae0y3yR83D9dUlkycOnmmlBAHKIZ9qUts9X7mWJf0+yy2QxJVpjaTGG\n\ cmnQKKPeNIhGJk2ENnnnzjEve7L7YJQF6itbx5VCOcsGh3Ocb3YR7DMdWjt7f8pu\n\ c6j+q1rP7EpE2afUN/geSlp5i3x8aXZPDj67jImbVCE/Q1X9voCtyzGJH7MXR0N9\n\ ZpRF8yzveRfMH8bwAJjSOGAFF5XkcR/RNY95o+J+QcgBLdX48h+ZdNmUf6jqlu3J\n\ 7KmTXXQcOVpN6dD3CmRFsbjq+x6RHwa8u1iGn+oIkX908r97ckfB/kHKH7ZdXIJc\n\ cpxtDQQMGYFpXK/71stq\n\ =ozeK\n\ -----END PGP SIGNATURE-----"; const char *data = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\ parent 8496071c1b46c854b31185ea97743be6a8774479\n\ author Ben Burkert <[email protected]> 1358451456 -0800\n\ committer Ben Burkert <[email protected]> 1358451456 -0800\n\ \n\ a simple commit which works\n"; const char *complete = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\ parent 8496071c1b46c854b31185ea97743be6a8774479\n\ author Ben Burkert <[email protected]> 1358451456 -0800\n\ committer Ben Burkert <[email protected]> 1358451456 -0800\n\ gpgsig -----BEGIN PGP SIGNATURE-----\n\ Version: GnuPG v1.4.12 (Darwin)\n\ \n\ iQIcBAABAgAGBQJQ+FMIAAoJEH+LfPdZDSs1e3EQAJMjhqjWF+WkGLHju7pTw2al\n\ o6IoMAhv0Z/LHlWhzBd9e7JeCnanRt12bAU7yvYp9+Z+z+dbwqLwDoFp8LVuigl8\n\ JGLcnwiUW3rSvhjdCp9irdb4+bhKUnKUzSdsR2CK4/hC0N2i/HOvMYX+BRsvqweq\n\ AsAkA6dAWh+gAfedrBUkCTGhlNYoetjdakWqlGL1TiKAefEZrtA1TpPkGn92vbLq\n\ SphFRUY9hVn1ZBWrT3hEpvAIcZag3rTOiRVT1X1flj8B2vGCEr3RrcwOIZikpdaW\n\ who/X3xh/DGbI2RbuxmmJpxxP/8dsVchRJJzBwG+yhwU/iN3MlV2c5D69tls/Dok\n\ 6VbyU4lm/ae0y3yR83D9dUlkycOnmmlBAHKIZ9qUts9X7mWJf0+yy2QxJVpjaTGG\n\ cmnQKKPeNIhGJk2ENnnnzjEve7L7YJQF6itbx5VCOcsGh3Ocb3YR7DMdWjt7f8pu\n\ c6j+q1rP7EpE2afUN/geSlp5i3x8aXZPDj67jImbVCE/Q1X9voCtyzGJH7MXR0N9\n\ ZpRF8yzveRfMH8bwAJjSOGAFF5XkcR/RNY95o+J+QcgBLdX48h+ZdNmUf6jqlu3J\n\ 7KmTXXQcOVpN6dD3CmRFsbjq+x6RHwa8u1iGn+oIkX908r97ckfB/kHKH7ZdXIJc\n\ cpxtDQQMGYFpXK/71stq\n\ =ozeK\n\ -----END PGP SIGNATURE-----\n\ \n\ a simple commit which works\n"; git_oid one, two; git_odb *odb; git_odb_object *obj; cl_git_pass(git_commit_create_with_signature(&one, g_repo, data, gpgsig, "gpgsig")); cl_git_pass(git_commit_create_with_signature(&two, g_repo, data, gpgsig, NULL)); cl_assert(!git_oid_cmp(&one, &two)); cl_git_pass(git_repository_odb(&odb, g_repo)); cl_git_pass(git_odb_read(&obj, odb, &one)); cl_assert_equal_s(complete, git_odb_object_data(obj)); git_odb_object_free(obj); git_odb_free(odb); }
libgit2-main
tests/libgit2/commit/write.c
#include "clar_libgit2.h" #include "delta.h" void test_delta_apply__read_at_off(void) { unsigned char base[16] = { 0 }, delta[] = { 0x10, 0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0x10, 0x00, 0x00 }; void *out; size_t outlen; cl_git_fail(git_delta_apply(&out, &outlen, base, sizeof(base), delta, sizeof(delta))); } void test_delta_apply__read_after_limit(void) { unsigned char base[16] = { 0 }, delta[] = { 0x10, 0x70, 0xff }; void *out; size_t outlen; cl_git_fail(git_delta_apply(&out, &outlen, base, sizeof(base), delta, sizeof(delta))); }
libgit2-main
tests/libgit2/delta/apply.c
#include "clar.h" #include "clar_libgit2.h" #include "git2/revert.h" #include "../merge/merge_helpers.h" #define TEST_REPO_PATH "revert-rename.git" static git_repository *repo; /* Fixture setup and teardown */ void test_revert_rename__initialize(void) { repo = cl_git_sandbox_init(TEST_REPO_PATH); } void test_revert_rename__cleanup(void) { cl_git_sandbox_cleanup(); } /* Attempt a revert when there is a file rename AND change of file mode, * but the file contents remain the same. Check that the file mode doesn't * change following the revert. */ void test_revert_rename__automerge(void) { git_commit *head_commit, *revert_commit; git_oid revert_oid; git_index *index; git_reference *head_ref; struct merge_index_entry merge_index_entries[] = { { 0100644, "f0f64c618e1646d2948a456ed7c4bcfad5536d68", 0, "goodmode" }}; cl_git_pass(git_repository_head(&head_ref, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head_ref, GIT_OBJECT_COMMIT)); cl_git_pass(git_oid__fromstr(&revert_oid, "7b4d7c3789b3581973c04087cb774c3c3576de2f", GIT_OID_SHA1)); cl_git_pass(git_commit_lookup(&revert_commit, repo, &revert_oid)); cl_git_pass(git_revert_commit(&index, repo, revert_commit, head_commit, 0, NULL)); cl_assert(merge_test_index(index, merge_index_entries, 1)); git_commit_free(revert_commit); git_commit_free(head_commit); git_index_free(index); git_reference_free(head_ref); }
libgit2-main
tests/libgit2/revert/rename.c
#include "clar.h" #include "clar_libgit2.h" #include "futils.h" #include "git2/revert.h" #include "../merge/merge_helpers.h" #define TEST_REPO_PATH "revert" static git_repository *repo; /* Fixture setup and teardown */ void test_revert_bare__initialize(void) { repo = cl_git_sandbox_init(TEST_REPO_PATH); } void test_revert_bare__cleanup(void) { cl_git_sandbox_cleanup(); } void test_revert_bare__automerge(void) { git_commit *head_commit, *revert_commit; git_oid head_oid, revert_oid; git_index *index; struct merge_index_entry merge_index_entries[] = { { 0100644, "caf99de3a49827117bb66721010eac461b06a80c", 0, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 0, "file6.txt" }, }; git_oid__fromstr(&head_oid, "72333f47d4e83616630ff3b0ffe4c0faebcc3c45", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head_commit, repo, &head_oid)); git_oid__fromstr(&revert_oid, "d1d403d22cbe24592d725f442835cf46fe60c8ac", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&revert_commit, repo, &revert_oid)); cl_git_pass(git_revert_commit(&index, repo, revert_commit, head_commit, 0, NULL)); cl_assert(merge_test_index(index, merge_index_entries, 4)); git_commit_free(revert_commit); git_commit_free(head_commit); git_index_free(index); } void test_revert_bare__conflicts(void) { git_reference *head_ref; git_commit *head_commit, *revert_commit; git_oid revert_oid; git_index *index; struct merge_index_entry merge_index_entries[] = { { 0100644, "7731926a337c4eaba1e2187d90ebfa0a93659382", 1, "file1.txt" }, { 0100644, "4b8fcff56437e60f58e9a6bc630dd242ebf6ea2c", 2, "file1.txt" }, { 0100644, "3a3ef367eaf3fe79effbfb0a56b269c04c2b59fe", 3, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 0, "file6.txt" }, }; git_oid__fromstr(&revert_oid, "72333f47d4e83616630ff3b0ffe4c0faebcc3c45", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head_ref, repo)); cl_git_pass(git_reference_peel((git_object **)&head_commit, head_ref, GIT_OBJECT_COMMIT)); cl_git_pass(git_commit_lookup(&revert_commit, repo, &revert_oid)); cl_git_pass(git_revert_commit(&index, repo, revert_commit, head_commit, 0, NULL)); cl_assert(git_index_has_conflicts(index)); cl_assert(merge_test_index(index, merge_index_entries, 6)); git_commit_free(revert_commit); git_commit_free(head_commit); git_reference_free(head_ref); git_index_free(index); } void test_revert_bare__orphan(void) { git_commit *head_commit, *revert_commit; git_oid head_oid, revert_oid; git_index *index; struct merge_index_entry merge_index_entries[] = { { 0100644, "296a6d3be1dff05c5d1f631d2459389fa7b619eb", 0, "file-mainline.txt" }, }; git_oid__fromstr(&head_oid, "39467716290f6df775a91cdb9a4eb39295018145", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head_commit, repo, &head_oid)); git_oid__fromstr(&revert_oid, "ebb03002cee5d66c7732dd06241119fe72ab96a5", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&revert_commit, repo, &revert_oid)); cl_git_pass(git_revert_commit(&index, repo, revert_commit, head_commit, 0, NULL)); cl_assert(merge_test_index(index, merge_index_entries, 1)); git_commit_free(revert_commit); git_commit_free(head_commit); git_index_free(index); }
libgit2-main
tests/libgit2/revert/bare.c
#include "clar.h" #include "clar_libgit2.h" #include "futils.h" #include "git2/revert.h" #include "../merge/merge_helpers.h" #define TEST_REPO_PATH "revert" static git_repository *repo; static git_index *repo_index; /* Fixture setup and teardown */ void test_revert_workdir__initialize(void) { git_config *cfg; repo = cl_git_sandbox_init(TEST_REPO_PATH); git_repository_index(&repo_index, repo); /* Ensure that the user's merge.conflictstyle doesn't interfere */ cl_git_pass(git_repository_config(&cfg, repo)); cl_git_pass(git_config_set_string(cfg, "merge.conflictstyle", "merge")); git_config_free(cfg); } void test_revert_workdir__cleanup(void) { git_index_free(repo_index); cl_git_sandbox_cleanup(); } /* git reset --hard 72333f47d4e83616630ff3b0ffe4c0faebcc3c45 * git revert --no-commit d1d403d22cbe24592d725f442835cf46fe60c8ac */ void test_revert_workdir__automerge(void) { git_commit *head, *commit; git_oid head_oid, revert_oid; struct merge_index_entry merge_index_entries[] = { { 0100644, "caf99de3a49827117bb66721010eac461b06a80c", 0, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 0, "file6.txt" }, }; git_oid__fromstr(&head_oid, "72333f47d4e83616630ff3b0ffe4c0faebcc3c45", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); cl_git_pass(git_reset(repo, (git_object *)head, GIT_RESET_HARD, NULL)); git_oid__fromstr(&revert_oid, "d1d403d22cbe24592d725f442835cf46fe60c8ac", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &revert_oid)); cl_git_pass(git_revert(repo, commit, NULL)); cl_assert(merge_test_index(repo_index, merge_index_entries, 4)); git_commit_free(commit); git_commit_free(head); } /* git revert --no-commit 72333f47d4e83616630ff3b0ffe4c0faebcc3c45 */ void test_revert_workdir__conflicts(void) { git_reference *head_ref; git_commit *head, *commit; git_oid revert_oid; git_str conflicting_buf = GIT_STR_INIT, mergemsg_buf = GIT_STR_INIT; struct merge_index_entry merge_index_entries[] = { { 0100644, "7731926a337c4eaba1e2187d90ebfa0a93659382", 1, "file1.txt" }, { 0100644, "4b8fcff56437e60f58e9a6bc630dd242ebf6ea2c", 2, "file1.txt" }, { 0100644, "3a3ef367eaf3fe79effbfb0a56b269c04c2b59fe", 3, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 0, "file6.txt" }, }; git_oid__fromstr(&revert_oid, "72333f47d4e83616630ff3b0ffe4c0faebcc3c45", GIT_OID_SHA1); cl_git_pass(git_repository_head(&head_ref, repo)); cl_git_pass(git_reference_peel((git_object **)&head, head_ref, GIT_OBJECT_COMMIT)); cl_git_pass(git_reset(repo, (git_object *)head, GIT_RESET_HARD, NULL)); cl_git_pass(git_commit_lookup(&commit, repo, &revert_oid)); cl_git_pass(git_revert(repo, commit, NULL)); cl_assert(merge_test_index(repo_index, merge_index_entries, 6)); cl_git_pass(git_futils_readbuffer(&conflicting_buf, TEST_REPO_PATH "/file1.txt")); cl_assert(strcmp(conflicting_buf.ptr, "!File one!\n" \ "!File one!\n" \ "File one!\n" \ "File one\n" \ "File one\n" \ "File one\n" \ "File one\n" \ "File one\n" \ "File one\n" \ "File one\n" \ "<<<<<<< HEAD\n" \ "File one!\n" \ "!File one!\n" \ "!File one!\n" \ "!File one!\n" \ "=======\n" \ "File one\n" \ "File one\n" \ "File one\n" \ "File one\n" \ ">>>>>>> parent of 72333f4... automergeable changes\n") == 0); cl_assert(git_fs_path_exists(TEST_REPO_PATH "/.git/MERGE_MSG")); cl_git_pass(git_futils_readbuffer(&mergemsg_buf, TEST_REPO_PATH "/.git/MERGE_MSG")); cl_assert(strcmp(mergemsg_buf.ptr, "Revert \"automergeable changes\"\n" \ "\n" \ "This reverts commit 72333f47d4e83616630ff3b0ffe4c0faebcc3c45.\n" "\n" \ "#Conflicts:\n" \ "#\tfile1.txt\n") == 0); git_commit_free(commit); git_commit_free(head); git_reference_free(head_ref); git_str_dispose(&mergemsg_buf); git_str_dispose(&conflicting_buf); } /* git reset --hard 39467716290f6df775a91cdb9a4eb39295018145 * git revert --no-commit ebb03002cee5d66c7732dd06241119fe72ab96a5 */ void test_revert_workdir__orphan(void) { git_commit *head, *commit; git_oid head_oid, revert_oid; struct merge_index_entry merge_index_entries[] = { { 0100644, "296a6d3be1dff05c5d1f631d2459389fa7b619eb", 0, "file-mainline.txt" }, }; git_oid__fromstr(&head_oid, "39467716290f6df775a91cdb9a4eb39295018145", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); cl_git_pass(git_reset(repo, (git_object *)head, GIT_RESET_HARD, NULL)); git_oid__fromstr(&revert_oid, "ebb03002cee5d66c7732dd06241119fe72ab96a5", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &revert_oid)); cl_git_pass(git_revert(repo, commit, NULL)); cl_assert(merge_test_index(repo_index, merge_index_entries, 1)); git_commit_free(commit); git_commit_free(head); } /* * revert the same commit twice (when the first reverts cleanly): * * git revert 2d440f2 * git revert 2d440f2 */ void test_revert_workdir__again(void) { git_reference *head_ref; git_commit *orig_head; git_tree *reverted_tree; git_oid reverted_tree_oid, reverted_commit_oid; git_signature *signature; struct merge_index_entry merge_index_entries[] = { { 0100644, "7731926a337c4eaba1e2187d90ebfa0a93659382", 0, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 0, "file6.txt" }, }; cl_git_pass(git_repository_head(&head_ref, repo)); cl_git_pass(git_reference_peel((git_object **)&orig_head, head_ref, GIT_OBJECT_COMMIT)); cl_git_pass(git_reset(repo, (git_object *)orig_head, GIT_RESET_HARD, NULL)); cl_git_pass(git_revert(repo, orig_head, NULL)); cl_assert(merge_test_index(repo_index, merge_index_entries, 4)); cl_git_pass(git_index_write_tree(&reverted_tree_oid, repo_index)); cl_git_pass(git_tree_lookup(&reverted_tree, repo, &reverted_tree_oid)); cl_git_pass(git_signature_new(&signature, "Reverter", "[email protected]", time(NULL), 0)); cl_git_pass(git_commit_create(&reverted_commit_oid, repo, "HEAD", signature, signature, NULL, "Reverted!", reverted_tree, 1, (const git_commit **)&orig_head)); cl_git_pass(git_revert(repo, orig_head, NULL)); cl_assert(merge_test_index(repo_index, merge_index_entries, 4)); git_signature_free(signature); git_tree_free(reverted_tree); git_commit_free(orig_head); git_reference_free(head_ref); } /* git reset --hard 72333f47d4e83616630ff3b0ffe4c0faebcc3c45 * git revert --no-commit d1d403d22cbe24592d725f442835cf46fe60c8ac */ void test_revert_workdir__again_after_automerge(void) { git_commit *head, *commit; git_tree *reverted_tree; git_oid head_oid, revert_oid, reverted_tree_oid, reverted_commit_oid; git_signature *signature; struct merge_index_entry merge_index_entries[] = { { 0100644, "caf99de3a49827117bb66721010eac461b06a80c", 0, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 0, "file6.txt" }, }; struct merge_index_entry second_revert_entries[] = { { 0100644, "3a3ef367eaf3fe79effbfb0a56b269c04c2b59fe", 1, "file1.txt" }, { 0100644, "caf99de3a49827117bb66721010eac461b06a80c", 2, "file1.txt" }, { 0100644, "747726e021bc5f44b86de60e3032fd6f9f1b8383", 3, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 0, "file6.txt" }, }; git_oid__fromstr(&head_oid, "72333f47d4e83616630ff3b0ffe4c0faebcc3c45", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); cl_git_pass(git_reset(repo, (git_object *)head, GIT_RESET_HARD, NULL)); git_oid__fromstr(&revert_oid, "d1d403d22cbe24592d725f442835cf46fe60c8ac", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &revert_oid)); cl_git_pass(git_revert(repo, commit, NULL)); cl_assert(merge_test_index(repo_index, merge_index_entries, 4)); cl_git_pass(git_index_write_tree(&reverted_tree_oid, repo_index)); cl_git_pass(git_tree_lookup(&reverted_tree, repo, &reverted_tree_oid)); cl_git_pass(git_signature_new(&signature, "Reverter", "[email protected]", time(NULL), 0)); cl_git_pass(git_commit_create(&reverted_commit_oid, repo, "HEAD", signature, signature, NULL, "Reverted!", reverted_tree, 1, (const git_commit **)&head)); cl_git_pass(git_revert(repo, commit, NULL)); cl_assert(merge_test_index(repo_index, second_revert_entries, 6)); git_signature_free(signature); git_tree_free(reverted_tree); git_commit_free(commit); git_commit_free(head); } /* * revert the same commit twice (when the first reverts cleanly): * * git revert 2d440f2 * git revert 2d440f2 */ void test_revert_workdir__again_after_edit(void) { git_reference *head_ref; git_commit *orig_head, *commit; git_tree *reverted_tree; git_oid orig_head_oid, revert_oid, reverted_tree_oid, reverted_commit_oid; git_signature *signature; struct merge_index_entry merge_index_entries[] = { { 0100644, "3721552e06c4bdc7d478e0674e6304888545d5fd", 0, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 0, "file6.txt" }, }; cl_git_pass(git_repository_head(&head_ref, repo)); cl_git_pass(git_oid__fromstr(&orig_head_oid, "399fb3aba3d9d13f7d40a9254ce4402067ef3149", GIT_OID_SHA1)); cl_git_pass(git_commit_lookup(&orig_head, repo, &orig_head_oid)); cl_git_pass(git_reset(repo, (git_object *)orig_head, GIT_RESET_HARD, NULL)); cl_git_pass(git_oid__fromstr(&revert_oid, "2d440f2b3147d3dc7ad1085813478d6d869d5a4d", GIT_OID_SHA1)); cl_git_pass(git_commit_lookup(&commit, repo, &revert_oid)); cl_git_pass(git_revert(repo, commit, NULL)); cl_assert(merge_test_index(repo_index, merge_index_entries, 4)); cl_git_pass(git_index_write_tree(&reverted_tree_oid, repo_index)); cl_git_pass(git_tree_lookup(&reverted_tree, repo, &reverted_tree_oid)); cl_git_pass(git_signature_new(&signature, "Reverter", "[email protected]", time(NULL), 0)); cl_git_pass(git_commit_create(&reverted_commit_oid, repo, "HEAD", signature, signature, NULL, "Reverted!", reverted_tree, 1, (const git_commit **)&orig_head)); cl_git_pass(git_revert(repo, commit, NULL)); cl_assert(merge_test_index(repo_index, merge_index_entries, 4)); git_signature_free(signature); git_tree_free(reverted_tree); git_commit_free(commit); git_commit_free(orig_head); git_reference_free(head_ref); } /* * revert the same commit twice (when the first reverts cleanly): * * git reset --hard 75ec9929465623f17ff3ad68c0438ea56faba815 * git revert 97e52d5e81f541080cd6b92829fb85bc4d81d90b */ void test_revert_workdir__again_after_edit_two(void) { git_str diff_buf = GIT_STR_INIT; git_config *config; git_oid head_commit_oid, revert_commit_oid; git_commit *head_commit, *revert_commit; struct merge_index_entry merge_index_entries[] = { { 0100644, "a8c86221b400b836010567cc3593db6e96c1a83a", 1, "file.txt" }, { 0100644, "46ff0854663aeb2182b9838c8da68e33ac23bc1e", 2, "file.txt" }, { 0100644, "21a96a98ed84d45866e1de6e266fd3a61a4ae9dc", 3, "file.txt" }, }; cl_git_pass(git_repository_config(&config, repo)); cl_git_pass(git_config_set_bool(config, "core.autocrlf", 0)); cl_git_pass(git_oid__fromstr(&head_commit_oid, "75ec9929465623f17ff3ad68c0438ea56faba815", GIT_OID_SHA1)); cl_git_pass(git_commit_lookup(&head_commit, repo, &head_commit_oid)); cl_git_pass(git_reset(repo, (git_object *)head_commit, GIT_RESET_HARD, NULL)); cl_git_pass(git_oid__fromstr(&revert_commit_oid, "97e52d5e81f541080cd6b92829fb85bc4d81d90b", GIT_OID_SHA1)); cl_git_pass(git_commit_lookup(&revert_commit, repo, &revert_commit_oid)); cl_git_pass(git_revert(repo, revert_commit, NULL)); cl_assert(merge_test_index(repo_index, merge_index_entries, 3)); cl_git_pass(git_futils_readbuffer(&diff_buf, "revert/file.txt")); cl_assert_equal_s( "a\n" \ "<<<<<<< HEAD\n" \ "=======\n" \ "a\n" \ ">>>>>>> parent of 97e52d5... Revert me\n" \ "a\n" \ "a\n" \ "a\n" \ "a\n" \ "ab", diff_buf.ptr); git_commit_free(revert_commit); git_commit_free(head_commit); git_config_free(config); git_str_dispose(&diff_buf); } /* git reset --hard 72333f47d4e83616630ff3b0ffe4c0faebcc3c45 * git revert --no-commit d1d403d22cbe24592d725f442835cf46fe60c8ac */ void test_revert_workdir__conflict_use_ours(void) { git_commit *head, *commit; git_oid head_oid, revert_oid; git_revert_options opts = GIT_REVERT_OPTIONS_INIT; struct merge_index_entry merge_index_entries[] = { { 0100644, "caf99de3a49827117bb66721010eac461b06a80c", 0, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 0, "file6.txt" }, }; struct merge_index_entry merge_filesystem_entries[] = { { 0100644, "caf99de3a49827117bb66721010eac461b06a80c", 0, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 0, "file6.txt" }, }; opts.checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE | GIT_CHECKOUT_USE_OURS; git_oid__fromstr(&head_oid, "72333f47d4e83616630ff3b0ffe4c0faebcc3c45", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); cl_git_pass(git_reset(repo, (git_object *)head, GIT_RESET_HARD, NULL)); git_oid__fromstr(&revert_oid, "d1d403d22cbe24592d725f442835cf46fe60c8ac", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &revert_oid)); cl_git_pass(git_revert(repo, commit, &opts)); cl_assert(merge_test_index(repo_index, merge_index_entries, 4)); cl_assert(merge_test_workdir(repo, merge_filesystem_entries, 4)); git_commit_free(commit); git_commit_free(head); } /* git reset --hard cef56612d71a6af8d8015691e4865f7fece905b5 * git revert --no-commit 55568c8de5322ff9a95d72747a239cdb64a19965 */ void test_revert_workdir__rename_1_of_2(void) { git_commit *head, *commit; git_oid head_oid, revert_oid; git_revert_options opts = GIT_REVERT_OPTIONS_INIT; struct merge_index_entry merge_index_entries[] = { { 0100644, "747726e021bc5f44b86de60e3032fd6f9f1b8383", 0, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "55acf326a69f0aab7a974ec53ffa55a50bcac14e", 3, "file4.txt" }, { 0100644, "55acf326a69f0aab7a974ec53ffa55a50bcac14e", 1, "file5.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 2, "file6.txt" }, }; opts.merge_opts.flags |= GIT_MERGE_FIND_RENAMES; opts.merge_opts.rename_threshold = 50; git_oid__fromstr(&head_oid, "cef56612d71a6af8d8015691e4865f7fece905b5", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); cl_git_pass(git_reset(repo, (git_object *)head, GIT_RESET_HARD, NULL)); git_oid__fromstr(&revert_oid, "55568c8de5322ff9a95d72747a239cdb64a19965", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &revert_oid)); cl_git_pass(git_revert(repo, commit, &opts)); cl_assert(merge_test_index(repo_index, merge_index_entries, 6)); git_commit_free(commit); git_commit_free(head); } /* git reset --hard 55568c8de5322ff9a95d72747a239cdb64a19965 * git revert --no-commit HEAD~1 */ void test_revert_workdir__rename(void) { git_commit *head, *commit; git_oid head_oid, revert_oid; git_revert_options opts = GIT_REVERT_OPTIONS_INIT; struct merge_index_entry merge_index_entries[] = { { 0100644, "55acf326a69f0aab7a974ec53ffa55a50bcac14e", 1, "file4.txt" }, { 0100644, "55acf326a69f0aab7a974ec53ffa55a50bcac14e", 2, "file5.txt" }, }; struct merge_name_entry merge_name_entries[] = { { "file4.txt", "file5.txt", "" }, }; opts.merge_opts.flags |= GIT_MERGE_FIND_RENAMES; opts.merge_opts.rename_threshold = 50; git_oid__fromstr(&head_oid, "55568c8de5322ff9a95d72747a239cdb64a19965", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); cl_git_pass(git_reset(repo, (git_object *)head, GIT_RESET_HARD, NULL)); git_oid__fromstr(&revert_oid, "0aa8c7e40d342fff78d60b29a4ba8e993ed79c51", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &revert_oid)); cl_git_pass(git_revert(repo, commit, &opts)); cl_assert(merge_test_index(repo_index, merge_index_entries, 2)); cl_assert(merge_test_names(repo_index, merge_name_entries, 1)); git_commit_free(commit); git_commit_free(head); } /* git revert --no-commit HEAD */ void test_revert_workdir__head(void) { git_reference *head; git_commit *commit; struct merge_index_entry merge_index_entries[] = { { 0100644, "7731926a337c4eaba1e2187d90ebfa0a93659382", 0, "file1.txt" }, { 0100644, "0ab09ea6d4c3634bdf6c221626d8b6f7dd890767", 0, "file2.txt" }, { 0100644, "f4e107c230d08a60fb419d19869f1f282b272d9c", 0, "file3.txt" }, { 0100644, "0f5bfcf58c558d865da6be0281d7795993646cee", 0, "file6.txt" }, }; /* HEAD is 2d440f2b3147d3dc7ad1085813478d6d869d5a4d */ cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&commit, head, GIT_OBJECT_COMMIT)); cl_git_pass(git_reset(repo, (git_object *)commit, GIT_RESET_HARD, NULL)); cl_git_pass(git_revert(repo, commit, NULL)); cl_assert(merge_test_index(repo_index, merge_index_entries, 4)); cl_assert(merge_test_workdir(repo, merge_index_entries, 4)); git_reference_free(head); git_commit_free(commit); } void test_revert_workdir__nonmerge_fails_mainline_specified(void) { git_reference *head; git_commit *commit; git_revert_options opts = GIT_REVERT_OPTIONS_INIT; cl_git_pass(git_repository_head(&head, repo)); cl_git_pass(git_reference_peel((git_object **)&commit, head, GIT_OBJECT_COMMIT)); opts.mainline = 1; cl_must_fail(git_revert(repo, commit, &opts)); cl_assert(!git_fs_path_exists(TEST_REPO_PATH "/.git/MERGE_MSG")); cl_assert(!git_fs_path_exists(TEST_REPO_PATH "/.git/REVERT_HEAD")); git_reference_free(head); git_commit_free(commit); } /* git reset --hard 5acdc74af27172ec491d213ee36cea7eb9ef2579 * git revert HEAD */ void test_revert_workdir__merge_fails_without_mainline_specified(void) { git_commit *head; git_oid head_oid; git_oid__fromstr(&head_oid, "5acdc74af27172ec491d213ee36cea7eb9ef2579", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); cl_git_pass(git_reset(repo, (git_object *)head, GIT_RESET_HARD, NULL)); cl_must_fail(git_revert(repo, head, NULL)); cl_assert(!git_fs_path_exists(TEST_REPO_PATH "/.git/MERGE_MSG")); cl_assert(!git_fs_path_exists(TEST_REPO_PATH "/.git/REVERT_HEAD")); git_commit_free(head); } /* git reset --hard 5acdc74af27172ec491d213ee36cea7eb9ef2579 * git revert HEAD -m1 --no-commit */ void test_revert_workdir__merge_first_parent(void) { git_commit *head; git_oid head_oid; git_revert_options opts = GIT_REVERT_OPTIONS_INIT; struct merge_index_entry merge_index_entries[] = { { 0100644, "296a6d3be1dff05c5d1f631d2459389fa7b619eb", 0, "file-mainline.txt" }, { 0100644, "0cdb66192ee192f70f891f05a47636057420e871", 0, "file1.txt" }, { 0100644, "73ec36fa120f8066963a0bc9105bb273dbd903d7", 0, "file2.txt" }, }; opts.mainline = 1; git_oid__fromstr(&head_oid, "5acdc74af27172ec491d213ee36cea7eb9ef2579", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); cl_git_pass(git_reset(repo, (git_object *)head, GIT_RESET_HARD, NULL)); cl_git_pass(git_revert(repo, head, &opts)); cl_assert(merge_test_index(repo_index, merge_index_entries, 3)); git_commit_free(head); } void test_revert_workdir__merge_second_parent(void) { git_commit *head; git_oid head_oid; git_revert_options opts = GIT_REVERT_OPTIONS_INIT; struct merge_index_entry merge_index_entries[] = { { 0100644, "33c6fd981c49a2abf2971482089350bfc5cda8ea", 0, "file-branch.txt" }, { 0100644, "0cdb66192ee192f70f891f05a47636057420e871", 0, "file1.txt" }, { 0100644, "73ec36fa120f8066963a0bc9105bb273dbd903d7", 0, "file2.txt" }, }; opts.mainline = 2; git_oid__fromstr(&head_oid, "5acdc74af27172ec491d213ee36cea7eb9ef2579", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); cl_git_pass(git_reset(repo, (git_object *)head, GIT_RESET_HARD, NULL)); cl_git_pass(git_revert(repo, head, &opts)); cl_assert(merge_test_index(repo_index, merge_index_entries, 3)); git_commit_free(head); }
libgit2-main
tests/libgit2/revert/workdir.c
#include "clar_libgit2.h" #include "git2/sys/repository.h" #include "apply.h" #include "repository.h" #include "../patch/patch_common.h" static git_repository *repo = NULL; static git_diff_options binary_opts = GIT_DIFF_OPTIONS_INIT; void test_apply_fromdiff__initialize(void) { repo = cl_git_sandbox_init("renames"); binary_opts.flags |= GIT_DIFF_SHOW_BINARY; } void test_apply_fromdiff__cleanup(void) { cl_git_sandbox_cleanup(); } static int apply_gitbuf( const git_str *old, const char *oldname, const git_str *new, const char *newname, const char *patch_expected, const git_diff_options *diff_opts) { git_patch *patch; git_str result = GIT_STR_INIT; git_buf patchbuf = GIT_BUF_INIT; char *filename; unsigned int mode; int error; cl_git_pass(git_patch_from_buffers(&patch, old ? old->ptr : NULL, old ? old->size : 0, oldname, new ? new->ptr : NULL, new ? new->size : 0, newname, diff_opts)); if (patch_expected) { cl_git_pass(git_patch_to_buf(&patchbuf, patch)); cl_assert_equal_s(patch_expected, patchbuf.ptr); } error = git_apply__patch(&result, &filename, &mode, old ? old->ptr : NULL, old ? old->size : 0, patch, NULL); if (error == 0 && new == NULL) { cl_assert_equal_i(0, result.size); cl_assert_equal_p(NULL, filename); cl_assert_equal_i(0, mode); } else if (error == 0) { cl_assert_equal_s(new->ptr, result.ptr); cl_assert_equal_s(newname ? newname : oldname, filename); cl_assert_equal_i(0100644, mode); } git__free(filename); git_str_dispose(&result); git_buf_dispose(&patchbuf); git_patch_free(patch); return error; } static int apply_buf( const char *old, const char *oldname, const char *new, const char *newname, const char *patch_expected, const git_diff_options *diff_opts) { git_str o = GIT_STR_INIT, n = GIT_STR_INIT, *optr = NULL, *nptr = NULL; if (old) { o.ptr = (char *)old; o.size = strlen(old); optr = &o; } if (new) { n.ptr = (char *)new; n.size = strlen(new); nptr = &n; } return apply_gitbuf(optr, oldname, nptr, newname, patch_expected, diff_opts); } void test_apply_fromdiff__change_middle(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_CHANGE_MIDDLE, "file.txt", PATCH_ORIGINAL_TO_CHANGE_MIDDLE, NULL)); } void test_apply_fromdiff__change_middle_nocontext(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_CHANGE_MIDDLE, "file.txt", PATCH_ORIGINAL_TO_CHANGE_MIDDLE_NOCONTEXT, &diff_opts)); } void test_apply_fromdiff__change_firstline(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_CHANGE_FIRSTLINE, "file.txt", PATCH_ORIGINAL_TO_CHANGE_FIRSTLINE, NULL)); } void test_apply_fromdiff__lastline(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_CHANGE_LASTLINE, "file.txt", PATCH_ORIGINAL_TO_CHANGE_LASTLINE, NULL)); } void test_apply_fromdiff__change_middle_and_lastline_nocontext(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_CHANGE_MIDDLE_AND_LASTLINE, "file.txt", PATCH_ORIGINAL_TO_CHANGE_MIDDLE_AND_LASTLINE_NOCONTEXT, &diff_opts)); } void test_apply_fromdiff__prepend(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_PREPEND, "file.txt", PATCH_ORIGINAL_TO_PREPEND, NULL)); } void test_apply_fromdiff__prepend_nocontext(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_PREPEND, "file.txt", PATCH_ORIGINAL_TO_PREPEND_NOCONTEXT, &diff_opts)); } void test_apply_fromdiff__prepend_and_change(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_PREPEND_AND_CHANGE, "file.txt", PATCH_ORIGINAL_TO_PREPEND_AND_CHANGE, NULL)); } void test_apply_fromdiff__prepend_and_change_nocontext(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_PREPEND_AND_CHANGE, "file.txt", PATCH_ORIGINAL_TO_PREPEND_AND_CHANGE_NOCONTEXT, &diff_opts)); } void test_apply_fromdiff__delete_and_change(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_DELETE_AND_CHANGE, "file.txt", PATCH_ORIGINAL_TO_DELETE_AND_CHANGE, NULL)); } void test_apply_fromdiff__delete_and_change_nocontext(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_DELETE_AND_CHANGE, "file.txt", PATCH_ORIGINAL_TO_DELETE_AND_CHANGE_NOCONTEXT, &diff_opts)); } void test_apply_fromdiff__delete_firstline(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_DELETE_FIRSTLINE, "file.txt", PATCH_ORIGINAL_TO_DELETE_FIRSTLINE, NULL)); } void test_apply_fromdiff__append(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_APPEND, "file.txt", PATCH_ORIGINAL_TO_APPEND, NULL)); } void test_apply_fromdiff__append_nocontext(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_APPEND, "file.txt", PATCH_ORIGINAL_TO_APPEND_NOCONTEXT, &diff_opts)); } void test_apply_fromdiff__prepend_and_append(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_PREPEND_AND_APPEND, "file.txt", PATCH_ORIGINAL_TO_PREPEND_AND_APPEND, NULL)); } void test_apply_fromdiff__to_empty_file(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", "", NULL, PATCH_ORIGINAL_TO_EMPTY_FILE, NULL)); } void test_apply_fromdiff__from_empty_file(void) { cl_git_pass(apply_buf( "", NULL, FILE_ORIGINAL, "file.txt", PATCH_EMPTY_FILE_TO_ORIGINAL, NULL)); } void test_apply_fromdiff__add(void) { cl_git_pass(apply_buf( NULL, NULL, FILE_ORIGINAL, "file.txt", PATCH_ADD_ORIGINAL, NULL)); } void test_apply_fromdiff__delete(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", NULL, NULL, PATCH_DELETE_ORIGINAL, NULL)); } void test_apply_fromdiff__no_change(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_ORIGINAL, "file.txt", "", NULL)); } void test_apply_fromdiff__binary_add(void) { git_str newfile = GIT_STR_INIT; newfile.ptr = FILE_BINARY_DELTA_MODIFIED; newfile.size = FILE_BINARY_DELTA_MODIFIED_LEN; cl_git_pass(apply_gitbuf( NULL, NULL, &newfile, "binary.bin", NULL, &binary_opts)); } void test_apply_fromdiff__binary_no_change(void) { git_str original = GIT_STR_INIT; original.ptr = FILE_BINARY_DELTA_ORIGINAL; original.size = FILE_BINARY_DELTA_ORIGINAL_LEN; cl_git_pass(apply_gitbuf( &original, "binary.bin", &original, "binary.bin", "", &binary_opts)); } void test_apply_fromdiff__binary_change_delta(void) { git_str original = GIT_STR_INIT, modified = GIT_STR_INIT; original.ptr = FILE_BINARY_DELTA_ORIGINAL; original.size = FILE_BINARY_DELTA_ORIGINAL_LEN; modified.ptr = FILE_BINARY_DELTA_MODIFIED; modified.size = FILE_BINARY_DELTA_MODIFIED_LEN; cl_git_pass(apply_gitbuf( &original, "binary.bin", &modified, "binary.bin", NULL, &binary_opts)); } void test_apply_fromdiff__binary_change_literal(void) { git_str original = GIT_STR_INIT, modified = GIT_STR_INIT; original.ptr = FILE_BINARY_LITERAL_ORIGINAL; original.size = FILE_BINARY_LITERAL_ORIGINAL_LEN; modified.ptr = FILE_BINARY_LITERAL_MODIFIED; modified.size = FILE_BINARY_LITERAL_MODIFIED_LEN; cl_git_pass(apply_gitbuf( &original, "binary.bin", &modified, "binary.bin", NULL, &binary_opts)); } void test_apply_fromdiff__binary_delete(void) { git_str original = GIT_STR_INIT; original.ptr = FILE_BINARY_DELTA_MODIFIED; original.size = FILE_BINARY_DELTA_MODIFIED_LEN; cl_git_pass(apply_gitbuf( &original, "binary.bin", NULL, NULL, NULL, &binary_opts)); } void test_apply_fromdiff__patching_correctly_truncates_source(void) { git_str original = GIT_STR_INIT, patched = GIT_STR_INIT; git_patch *patch; unsigned int mode; char *path; cl_git_pass(git_patch_from_buffers(&patch, "foo\nbar", 7, "file.txt", "foo\nfoo", 7, "file.txt", NULL)); /* * Previously, we would fail to correctly truncate the source buffer if * the source has more than one line and ends with a non-newline * character. In the following call, we thus truncate the source string * in the middle of the second line. Without the bug fixed, we would * successfully apply the patch to the source and return success. With * the overflow being fixed, we should return an error. */ cl_git_fail_with(GIT_EAPPLYFAIL, git_apply__patch(&patched, &path, &mode, "foo\nbar\n", 5, patch, NULL)); /* Verify that the patch succeeds if we do not truncate */ cl_git_pass(git_apply__patch(&patched, &path, &mode, "foo\nbar\n", 7, patch, NULL)); git_str_dispose(&original); git_str_dispose(&patched); git_patch_free(patch); git__free(path); }
libgit2-main
tests/libgit2/apply/fromdiff.c
#include "clar_libgit2.h" #include "apply_helpers.h" static git_repository *repo; #define TEST_REPO_PATH "merge-recursive" void test_apply_both__initialize(void) { git_oid oid; git_commit *commit; repo = cl_git_sandbox_init(TEST_REPO_PATH); git_oid__fromstr(&oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &oid)); cl_git_pass(git_reset(repo, (git_object *)commit, GIT_RESET_HARD, NULL)); git_commit_free(commit); } void test_apply_both__cleanup(void) { cl_git_sandbox_cleanup(); } void test_apply_both__generated_diff(void) { git_oid a_oid, b_oid; git_commit *a_commit, *b_commit; git_tree *a_tree, *b_tree; git_diff *diff; git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; struct merge_index_entry both_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); git_oid__fromstr(&a_oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1); git_oid__fromstr(&b_oid, "7c7bf85e978f1d18c0566f702d2cb7766b9c8d4f", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&a_commit, repo, &a_oid)); cl_git_pass(git_commit_lookup(&b_commit, repo, &b_oid)); cl_git_pass(git_commit_tree(&a_tree, a_commit)); cl_git_pass(git_commit_tree(&b_tree, b_commit)); cl_git_pass(git_diff_tree_to_tree(&diff, repo, a_tree, b_tree, &diff_opts)); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); git_tree_free(a_tree); git_tree_free(b_tree); git_commit_free(a_commit); git_commit_free(b_commit); } void test_apply_both__parsed_diff(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_MODIFY_TWO_FILES, strlen(DIFF_MODIFY_TWO_FILES))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__removes_file(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_DELETE_FILE, strlen(DIFF_DELETE_FILE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__adds_file(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "6370543fcfedb3e6516ec53b06158f3687dc1447", 0, "newfile.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_ADD_FILE, strlen(DIFF_ADD_FILE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__application_failure_leaves_index_unmodified(void) { git_diff *diff; git_index *index; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry index_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); /* mutate the index */ cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_index_remove(index, "veal.txt", 0)); cl_git_pass(git_index_write(index)); git_index_free(index); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_fail_with(GIT_EAPPLYFAIL, git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_workdir_unchanged(repo); git_diff_free(diff); } void test_apply_both__index_must_match_workdir(void) { git_diff *diff; git_index *index; git_index_entry idx_entry; const char *diff_file = DIFF_MODIFY_TWO_FILES; /* * Append a line to the end of the file in both the index and the * working directory. Although the appended line would allow for * patch application in each, the line appended is different in * each, so the application should not be allowed. */ cl_git_append2file("merge-recursive/asparagus.txt", "This is a modification.\n"); cl_git_pass(git_repository_index(&index, repo)); memset(&idx_entry, 0, sizeof(git_index_entry)); idx_entry.mode = 0100644; idx_entry.path = "asparagus.txt"; cl_git_pass(git_oid__fromstr(&idx_entry.id, "06d3fefb8726ab1099acc76e02dfb85e034b2538", GIT_OID_SHA1)); cl_git_pass(git_index_add(index, &idx_entry)); cl_git_pass(git_index_write(index)); git_index_free(index); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_fail_with(GIT_EAPPLYFAIL, git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); git_diff_free(diff); } void test_apply_both__index_mode_must_match_workdir(void) { git_diff *diff; if (!cl_is_chmod_supported()) clar__skip(); /* Set a file in the working directory executable. */ cl_must_pass(p_chmod("merge-recursive/asparagus.txt", 0755)); cl_git_pass(git_diff_from_buffer(&diff, DIFF_MODIFY_TWO_FILES, strlen(DIFF_MODIFY_TWO_FILES))); cl_git_fail_with(GIT_EAPPLYFAIL, git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); git_diff_free(diff); } void test_apply_both__application_failure_leaves_workdir_unmodified(void) { git_diff *diff; git_index *index; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry workdir_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "8684724651336001c5dbce74bed6736d2443958d", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); /* mutate the workdir */ cl_git_rewritefile("merge-recursive/veal.txt", "This is a modification.\n"); cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_index_add_bypath(index, "veal.txt")); cl_git_pass(git_index_write(index)); git_index_free(index); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_fail_with(GIT_EAPPLYFAIL, git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } void test_apply_both__keeps_nonconflicting_changes(void) { git_diff *diff; git_index *index; git_index_entry idx_entry; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry index_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "898d12687fb35be271c27c795a6b32c8b51da79e", 0, "beef.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); struct merge_index_entry workdir_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "f75ba05f340c51065cbea2e1fdbfe5fe13144c97", 0, "gravy.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); /* mutate the index */ cl_git_pass(git_repository_index(&index, repo)); memset(&idx_entry, 0, sizeof(git_index_entry)); idx_entry.mode = 0100644; idx_entry.path = "beef.txt"; cl_git_pass(git_oid__fromstr(&idx_entry.id, "898d12687fb35be271c27c795a6b32c8b51da79e", GIT_OID_SHA1)); cl_git_pass(git_index_add(index, &idx_entry)); cl_git_pass(git_index_remove(index, "bouilli.txt", 0)); cl_git_pass(git_index_write(index)); git_index_free(index); /* and mutate the working directory */ cl_git_rmfile("merge-recursive/oyster.txt"); cl_git_rewritefile("merge-recursive/gravy.txt", "Hello, world.\n"); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } void test_apply_both__can_apply_nonconflicting_file_changes(void) { git_diff *diff; git_index *index; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry both_expected[] = { { 0100644, "f8a701c8a1a22c1729ee50faff1111f2d64f96fc", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); /* * Replace the workdir file with a version that is different than * HEAD but such that the patch still applies cleanly. This item * has a new line appended. */ cl_git_append2file("merge-recursive/asparagus.txt", "This line is added in the index and the workdir.\n"); cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_index_add_bypath(index, "asparagus.txt")); cl_git_pass(git_index_write(index)); git_index_free(index); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__honors_crlf_attributes(void) { git_diff *diff; git_oid oid; git_commit *commit; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry index_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); struct merge_index_entry workdir_expected[] = { { 0100644, "176a458f94e0ea5272ce67c36bf30b6be9caf623", 0, ".gitattributes" }, { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); cl_git_mkfile("merge-recursive/.gitattributes", "* text=auto\n"); cl_git_rmfile("merge-recursive/asparagus.txt"); cl_git_rmfile("merge-recursive/veal.txt"); git_oid__fromstr(&oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &oid)); cl_git_pass(git_reset(repo, (git_object *)commit, GIT_RESET_HARD, NULL)); git_commit_free(commit); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } void test_apply_both__rename(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "notbeef.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_RENAME_FILE, strlen(DIFF_RENAME_FILE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__rename_and_modify(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "6fa10147f00fe1fab1d5e835529a9dad53db8552", 0, "notbeef.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_RENAME_AND_MODIFY_FILE, strlen(DIFF_RENAME_AND_MODIFY_FILE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__rename_a_to_b_to_c(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "notbeef.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_RENAME_A_TO_B_TO_C, strlen(DIFF_RENAME_A_TO_B_TO_C))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__rename_a_to_b_to_c_exact(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "notbeef.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_RENAME_A_TO_B_TO_C_EXACT, strlen(DIFF_RENAME_A_TO_B_TO_C_EXACT))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__rename_circular(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "asparagus.txt" }, { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" } }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_RENAME_CIRCULAR, strlen(DIFF_RENAME_CIRCULAR))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__rename_2_to_1(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "2.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" } }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_RENAME_2_TO_1, strlen(DIFF_RENAME_2_TO_1))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__rename_1_to_2(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "1.txt" }, { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "2.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" } }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_RENAME_1_TO_2, strlen(DIFF_RENAME_1_TO_2))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__two_deltas_one_file(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "0a9fd4415635e72573f0f6b5e68084cfe18f5075", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" } }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_TWO_DELTAS_ONE_FILE, strlen(DIFF_TWO_DELTAS_ONE_FILE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__two_deltas_one_new_file(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "08d4c445cf0078f3d9b604b82f32f4d87e083325", 0, "newfile.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" } }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_TWO_DELTAS_ONE_NEW_FILE, strlen(DIFF_TWO_DELTAS_ONE_NEW_FILE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__rename_and_modify_deltas(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "61c686bed39684eee8a2757ceb1291004a21333f", 0, "asdf.txt" }, { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_RENAME_AND_MODIFY_DELTAS, strlen(DIFF_RENAME_AND_MODIFY_DELTAS))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__rename_delta_after_modify_delta(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "292cb60ce5e25c337c5b6e12957bbbfe1be4bf49", 0, "other.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "c8c120f466591bbe3b8867361d5ec3cdd9fda756", 0, "veal.txt" } }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_RENAME_AFTER_MODIFY, strlen(DIFF_RENAME_AFTER_MODIFY))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__cant_rename_after_modify_nonexistent_target_path(void) { git_diff *diff; cl_git_pass(git_diff_from_buffer(&diff, DIFF_RENAME_AFTER_MODIFY_TARGET_PATH, strlen(DIFF_RENAME_AFTER_MODIFY_TARGET_PATH))); cl_git_fail(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); git_diff_free(diff); } void test_apply_both__cant_modify_source_path_after_rename(void) { git_diff *diff; cl_git_pass(git_diff_from_buffer(&diff, DIFF_RENAME_AND_MODIFY_SOURCE_PATH, strlen(DIFF_RENAME_AND_MODIFY_SOURCE_PATH))); cl_git_fail(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); git_diff_free(diff); } void test_apply_both__readd_deleted_file(void) { git_diff *diff; struct merge_index_entry both_expected[] = { { 0100644, "2dc7f8b24ba27f3888368bd180df03ff4c6c6fab", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" } }; size_t both_expected_cnt = sizeof(both_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_DELETE_AND_READD_FILE, strlen(DIFF_DELETE_AND_READD_FILE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); validate_apply_index(repo, both_expected, both_expected_cnt); validate_apply_workdir(repo, both_expected, both_expected_cnt); git_diff_free(diff); } void test_apply_both__cant_remove_file_twice(void) { git_diff *diff; cl_git_pass(git_diff_from_buffer(&diff, DIFF_REMOVE_FILE_TWICE, strlen(DIFF_REMOVE_FILE_TWICE))); cl_git_fail(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); git_diff_free(diff); } void test_apply_both__cant_add_invalid_filename(void) { git_diff *diff; cl_git_pass(git_diff_from_buffer(&diff, DIFF_ADD_INVALID_FILENAME, strlen(DIFF_ADD_INVALID_FILENAME))); cl_git_fail(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, NULL)); git_diff_free(diff); }
libgit2-main
tests/libgit2/apply/both.c
#include "clar_libgit2.h" #include "apply_helpers.h" static git_repository *repo; #define TEST_REPO_PATH "merge-recursive" void test_apply_check__initialize(void) { git_oid oid; git_commit *commit; repo = cl_git_sandbox_init(TEST_REPO_PATH); git_oid__fromstr(&oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &oid)); cl_git_pass(git_reset(repo, (git_object *)commit, GIT_RESET_HARD, NULL)); git_commit_free(commit); } void test_apply_check__cleanup(void) { cl_git_sandbox_cleanup(); } void test_apply_check__generate_diff(void) { git_oid a_oid, b_oid; git_commit *a_commit, *b_commit; git_tree *a_tree, *b_tree; git_diff *diff; git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; git_apply_options opts = GIT_APPLY_OPTIONS_INIT; cl_git_pass(git_oid__fromstr(&a_oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1)); cl_git_pass(git_oid__fromstr(&b_oid, "7c7bf85e978f1d18c0566f702d2cb7766b9c8d4f", GIT_OID_SHA1)); cl_git_pass(git_commit_lookup(&a_commit, repo, &a_oid)); cl_git_pass(git_commit_lookup(&b_commit, repo, &b_oid)); cl_git_pass(git_commit_tree(&a_tree, a_commit)); cl_git_pass(git_commit_tree(&b_tree, b_commit)); opts.flags |= GIT_APPLY_CHECK; cl_git_pass(git_diff_tree_to_tree(&diff, repo, a_tree, b_tree, &diff_opts)); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_BOTH, &opts)); validate_index_unchanged(repo); validate_workdir_unchanged(repo); git_diff_free(diff); git_tree_free(a_tree); git_tree_free(b_tree); git_commit_free(a_commit); git_commit_free(b_commit); } void test_apply_check__parsed_diff(void) { git_diff *diff; git_apply_options opts = GIT_APPLY_OPTIONS_INIT; opts.flags |= GIT_APPLY_CHECK; cl_git_pass(git_diff_from_buffer(&diff, DIFF_MODIFY_TWO_FILES, strlen(DIFF_MODIFY_TWO_FILES))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, &opts)); validate_index_unchanged(repo); validate_workdir_unchanged(repo); git_diff_free(diff); } void test_apply_check__binary(void) { git_diff *diff; git_apply_options opts = GIT_APPLY_OPTIONS_INIT; opts.flags |= GIT_APPLY_CHECK; cl_git_pass(git_diff_from_buffer(&diff, DIFF_MODIFY_TWO_FILES_BINARY, strlen(DIFF_MODIFY_TWO_FILES_BINARY))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, &opts)); validate_index_unchanged(repo); validate_workdir_unchanged(repo); git_diff_free(diff); } void test_apply_check__does_not_apply(void) { git_diff *diff; git_index *index; git_apply_options opts = GIT_APPLY_OPTIONS_INIT; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry index_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); /* mutate the index */ cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_index_remove(index, "veal.txt", 0)); cl_git_pass(git_index_write(index)); git_index_free(index); opts.flags |= GIT_APPLY_CHECK; cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_fail_with(GIT_EAPPLYFAIL, git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, &opts)); validate_apply_index(repo, index_expected, index_expected_cnt); git_diff_free(diff); }
libgit2-main
tests/libgit2/apply/check.c
#include "clar_libgit2.h" #include "apply_helpers.h" struct iterator_compare_data { struct merge_index_entry *expected; size_t cnt; size_t idx; }; static int iterator_compare(const git_index_entry *entry, void *_data) { git_oid expected_id; struct iterator_compare_data *data = (struct iterator_compare_data *)_data; cl_assert_equal_i(GIT_INDEX_ENTRY_STAGE(entry), data->expected[data->idx].stage); cl_git_pass(git_oid__fromstr(&expected_id, data->expected[data->idx].oid_str, GIT_OID_SHA1)); cl_assert_equal_oid(&entry->id, &expected_id); cl_assert_equal_i(entry->mode, data->expected[data->idx].mode); cl_assert_equal_s(entry->path, data->expected[data->idx].path); if (data->idx >= data->cnt) return -1; data->idx++; return 0; } void validate_apply_workdir( git_repository *repo, struct merge_index_entry *workdir_entries, size_t workdir_cnt) { git_index *index; git_iterator *iterator; git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT; struct iterator_compare_data data = { workdir_entries, workdir_cnt }; opts.flags |= GIT_ITERATOR_INCLUDE_HASH; cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_iterator_for_workdir(&iterator, repo, index, NULL, &opts)); cl_git_pass(git_iterator_foreach(iterator, iterator_compare, &data)); cl_assert_equal_i(data.idx, data.cnt); git_iterator_free(iterator); git_index_free(index); } void validate_apply_index( git_repository *repo, struct merge_index_entry *index_entries, size_t index_cnt) { git_index *index; git_iterator *iterator; struct iterator_compare_data data = { index_entries, index_cnt }; cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_iterator_for_index(&iterator, repo, index, NULL)); cl_git_pass(git_iterator_foreach(iterator, iterator_compare, &data)); cl_assert_equal_i(data.idx, data.cnt); git_iterator_free(iterator); git_index_free(index); } static int iterator_eq(const git_index_entry **entry, void *_data) { GIT_UNUSED(_data); if (!entry[0] || !entry[1]) return -1; cl_assert_equal_i(GIT_INDEX_ENTRY_STAGE(entry[0]), GIT_INDEX_ENTRY_STAGE(entry[1])); cl_assert_equal_oid(&entry[0]->id, &entry[1]->id); cl_assert_equal_i(entry[0]->mode, entry[1]->mode); cl_assert_equal_s(entry[0]->path, entry[1]->path); return 0; } void validate_index_unchanged(git_repository *repo) { git_tree *head; git_index *index; git_iterator *head_iterator, *index_iterator, *iterators[2]; cl_git_pass(git_repository_head_tree(&head, repo)); cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_iterator_for_tree(&head_iterator, head, NULL)); cl_git_pass(git_iterator_for_index(&index_iterator, repo, index, NULL)); iterators[0] = head_iterator; iterators[1] = index_iterator; cl_git_pass(git_iterator_walk(iterators, 2, iterator_eq, NULL)); git_iterator_free(head_iterator); git_iterator_free(index_iterator); git_tree_free(head); git_index_free(index); } void validate_workdir_unchanged(git_repository *repo) { git_tree *head; git_index *index; git_iterator *head_iterator, *workdir_iterator, *iterators[2]; git_iterator_options workdir_opts = GIT_ITERATOR_OPTIONS_INIT; cl_git_pass(git_repository_head_tree(&head, repo)); cl_git_pass(git_repository_index(&index, repo)); workdir_opts.flags |= GIT_ITERATOR_INCLUDE_HASH; cl_git_pass(git_iterator_for_tree(&head_iterator, head, NULL)); cl_git_pass(git_iterator_for_workdir(&workdir_iterator, repo, index, NULL, &workdir_opts)); iterators[0] = head_iterator; iterators[1] = workdir_iterator; cl_git_pass(git_iterator_walk(iterators, 2, iterator_eq, NULL)); git_iterator_free(head_iterator); git_iterator_free(workdir_iterator); git_tree_free(head); git_index_free(index); }
libgit2-main
tests/libgit2/apply/apply_helpers.c
#include "clar_libgit2.h" #include "apply_helpers.h" static git_repository *repo; #define TEST_REPO_PATH "merge-recursive" void test_apply_index__initialize(void) { git_oid oid; git_commit *commit; repo = cl_git_sandbox_init(TEST_REPO_PATH); git_oid__fromstr(&oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &oid)); cl_git_pass(git_reset(repo, (git_object *)commit, GIT_RESET_HARD, NULL)); git_commit_free(commit); } void test_apply_index__cleanup(void) { cl_git_sandbox_cleanup(); } void test_apply_index__generate_diff(void) { git_oid a_oid, b_oid; git_commit *a_commit, *b_commit; git_tree *a_tree, *b_tree; git_diff *diff; git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; struct merge_index_entry index_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); git_oid__fromstr(&a_oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1); git_oid__fromstr(&b_oid, "7c7bf85e978f1d18c0566f702d2cb7766b9c8d4f", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&a_commit, repo, &a_oid)); cl_git_pass(git_commit_lookup(&b_commit, repo, &b_oid)); cl_git_pass(git_commit_tree(&a_tree, a_commit)); cl_git_pass(git_commit_tree(&b_tree, b_commit)); cl_git_pass(git_diff_tree_to_tree(&diff, repo, a_tree, b_tree, &diff_opts)); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_workdir_unchanged(repo); git_diff_free(diff); git_tree_free(a_tree); git_tree_free(b_tree); git_commit_free(a_commit); git_commit_free(b_commit); } void test_apply_index__parsed_diff(void) { git_diff *diff; struct merge_index_entry index_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_MODIFY_TWO_FILES, strlen(DIFF_MODIFY_TWO_FILES))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_workdir_unchanged(repo); git_diff_free(diff); } void test_apply_index__removes_file(void) { git_diff *diff; struct merge_index_entry index_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_DELETE_FILE, strlen(DIFF_DELETE_FILE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_workdir_unchanged(repo); git_diff_free(diff); } void test_apply_index__adds_file(void) { git_diff *diff; struct merge_index_entry index_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "6370543fcfedb3e6516ec53b06158f3687dc1447", 0, "newfile.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_ADD_FILE, strlen(DIFF_ADD_FILE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_workdir_unchanged(repo); git_diff_free(diff); } void test_apply_index__modified_workdir_with_unmodified_index_is_ok(void) { git_diff *diff; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry index_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); struct merge_index_entry workdir_expected[] = { { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "f75ba05f340c51065cbea2e1fdbfe5fe13144c97", 0, "veal.txt" } }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); /* mutate the workdir and leave the index matching HEAD */ cl_git_rmfile("merge-recursive/asparagus.txt"); cl_git_rewritefile("merge-recursive/veal.txt", "Hello, world.\n"); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } void test_apply_index__application_failure_leaves_index_unmodified(void) { git_diff *diff; git_index *index; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry index_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); /* mutate the index */ cl_git_pass(git_repository_index(&index, repo)); cl_git_pass(git_index_remove(index, "veal.txt", 0)); cl_git_pass(git_index_write(index)); git_index_free(index); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_fail_with(GIT_EAPPLYFAIL, git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); git_diff_free(diff); } void test_apply_index__keeps_nonconflicting_changes(void) { git_diff *diff; git_index *index; git_index_entry idx_entry; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry index_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "898d12687fb35be271c27c795a6b32c8b51da79e", 0, "beef.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); /* mutate the index */ cl_git_pass(git_repository_index(&index, repo)); memset(&idx_entry, 0, sizeof(git_index_entry)); idx_entry.mode = 0100644; idx_entry.path = "beef.txt"; cl_git_pass(git_oid__fromstr(&idx_entry.id, "898d12687fb35be271c27c795a6b32c8b51da79e", GIT_OID_SHA1)); cl_git_pass(git_index_add(index, &idx_entry)); cl_git_pass(git_index_remove(index, "bouilli.txt", 0)); cl_git_pass(git_index_write(index)); git_index_free(index); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_workdir_unchanged(repo); git_diff_free(diff); } void test_apply_index__can_apply_nonconflicting_file_changes(void) { git_diff *diff; git_index *index; git_index_entry idx_entry; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry index_expected[] = { { 0100644, "4f2d1645dee99ced096877911de540c65ade2ef8", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); /* * Replace the index entry with a version that is different than * HEAD but such that the patch still applies cleanly. This item * has a new line appended. */ cl_git_pass(git_repository_index(&index, repo)); memset(&idx_entry, 0, sizeof(git_index_entry)); idx_entry.mode = 0100644; idx_entry.path = "asparagus.txt"; cl_git_pass(git_oid__fromstr(&idx_entry.id, "06d3fefb8726ab1099acc76e02dfb85e034b2538", GIT_OID_SHA1)); cl_git_pass(git_index_add(index, &idx_entry)); cl_git_pass(git_index_write(index)); git_index_free(index); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_workdir_unchanged(repo); git_diff_free(diff); } void test_apply_index__change_mode(void) { git_diff *diff; const char *diff_file = DIFF_EXECUTABLE_FILE; struct merge_index_entry index_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100755, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_workdir_unchanged(repo); git_diff_free(diff); }
libgit2-main
tests/libgit2/apply/index.c
#include "clar_libgit2.h" #include "git2/sys/repository.h" #include "apply.h" #include "repository.h" #include "../patch/patch_common.h" static git_repository *repo = NULL; void test_apply_partial__initialize(void) { repo = cl_git_sandbox_init("renames"); } void test_apply_partial__cleanup(void) { cl_git_sandbox_cleanup(); } static int skip_addition( const git_diff_hunk *hunk, void *payload) { GIT_UNUSED(payload); return (hunk->new_lines > hunk->old_lines) ? 1 : 0; } static int skip_deletion( const git_diff_hunk *hunk, void *payload) { GIT_UNUSED(payload); return (hunk->new_lines < hunk->old_lines) ? 1 : 0; } static int skip_change( const git_diff_hunk *hunk, void *payload) { GIT_UNUSED(payload); return (hunk->new_lines == hunk->old_lines) ? 1 : 0; } static int abort_addition( const git_diff_hunk *hunk, void *payload) { GIT_UNUSED(payload); return (hunk->new_lines > hunk->old_lines) ? GIT_EUSER : 0; } static int abort_deletion( const git_diff_hunk *hunk, void *payload) { GIT_UNUSED(payload); return (hunk->new_lines < hunk->old_lines) ? GIT_EUSER : 0; } static int abort_change( const git_diff_hunk *hunk, void *payload) { GIT_UNUSED(payload); return (hunk->new_lines == hunk->old_lines) ? GIT_EUSER : 0; } static int apply_buf( const char *old, const char *oldname, const char *new, const char *newname, const char *expected, const git_diff_options *diff_opts, git_apply_hunk_cb hunk_cb, void *payload) { git_patch *patch; git_str result = GIT_STR_INIT; git_str patchbuf = GIT_STR_INIT; git_apply_options opts = GIT_APPLY_OPTIONS_INIT; char *filename; unsigned int mode; int error; size_t oldsize = strlen(old); size_t newsize = strlen(new); opts.hunk_cb = hunk_cb; opts.payload = payload; cl_git_pass(git_patch_from_buffers(&patch, old, oldsize, oldname, new, newsize, newname, diff_opts)); if ((error = git_apply__patch(&result, &filename, &mode, old, oldsize, patch, &opts)) == 0) { cl_assert_equal_s(expected, result.ptr); cl_assert_equal_s(newname, filename); cl_assert_equal_i(0100644, mode); } git__free(filename); git_str_dispose(&result); git_str_dispose(&patchbuf); git_patch_free(patch); return error; } void test_apply_partial__prepend_and_change_skip_addition(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_PREPEND_AND_CHANGE, "file.txt", FILE_ORIGINAL, NULL, skip_addition, NULL)); } void test_apply_partial__prepend_and_change_nocontext_skip_addition(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_PREPEND_AND_CHANGE, "file.txt", FILE_CHANGE_MIDDLE, &diff_opts, skip_addition, NULL)); } void test_apply_partial__prepend_and_change_nocontext_abort_addition(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_fail(apply_buf( FILE_ORIGINAL, "file.txt", FILE_PREPEND_AND_CHANGE, "file.txt", FILE_ORIGINAL, &diff_opts, abort_addition, NULL)); } void test_apply_partial__prepend_and_change_skip_change(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_PREPEND_AND_CHANGE, "file.txt", FILE_PREPEND_AND_CHANGE, NULL, skip_change, NULL)); } void test_apply_partial__prepend_and_change_nocontext_skip_change(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_PREPEND_AND_CHANGE, "file.txt", FILE_PREPEND, &diff_opts, skip_change, NULL)); } void test_apply_partial__prepend_and_change_nocontext_abort_change(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_fail(apply_buf( FILE_ORIGINAL, "file.txt", FILE_PREPEND_AND_CHANGE, "file.txt", FILE_PREPEND, &diff_opts, abort_change, NULL)); } void test_apply_partial__delete_and_change_skip_deletion(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_DELETE_AND_CHANGE, "file.txt", FILE_ORIGINAL, NULL, skip_deletion, NULL)); } void test_apply_partial__delete_and_change_nocontext_skip_deletion(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_DELETE_AND_CHANGE, "file.txt", FILE_CHANGE_MIDDLE, &diff_opts, skip_deletion, NULL)); } void test_apply_partial__delete_and_change_nocontext_abort_deletion(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_fail(apply_buf( FILE_ORIGINAL, "file.txt", FILE_DELETE_AND_CHANGE, "file.txt", FILE_ORIGINAL, &diff_opts, abort_deletion, NULL)); } void test_apply_partial__delete_and_change_skip_change(void) { cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_DELETE_AND_CHANGE, "file.txt", FILE_DELETE_AND_CHANGE, NULL, skip_change, NULL)); } void test_apply_partial__delete_and_change_nocontext_skip_change(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(apply_buf( FILE_ORIGINAL, "file.txt", FILE_DELETE_AND_CHANGE, "file.txt", FILE_DELETE_FIRSTLINE, &diff_opts, skip_change, NULL)); } void test_apply_partial__delete_and_change_nocontext_abort_change(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_fail(apply_buf( FILE_ORIGINAL, "file.txt", FILE_DELETE_AND_CHANGE, "file.txt", FILE_DELETE_FIRSTLINE, &diff_opts, abort_change, NULL)); }
libgit2-main
tests/libgit2/apply/partial.c
#include "clar_libgit2.h" #include "git2/sys/repository.h" #include "apply.h" #include "patch.h" #include "patch_parse.h" #include "repository.h" #include "../patch/patch_common.h" static git_repository *repo = NULL; void test_apply_fromfile__initialize(void) { repo = cl_git_sandbox_init("renames"); } void test_apply_fromfile__cleanup(void) { cl_git_sandbox_cleanup(); } static int apply_patchfile( const char *old, size_t old_len, const char *new, size_t new_len, const char *patchfile, const char *filename_expected, unsigned int mode_expected) { git_patch *patch; git_str result = GIT_STR_INIT; git_str patchbuf = GIT_STR_INIT; char *filename; unsigned int mode; int error; cl_git_pass(git_patch_from_buffer(&patch, patchfile, strlen(patchfile), NULL)); error = git_apply__patch(&result, &filename, &mode, old, old_len, patch, NULL); if (error == 0) { cl_assert_equal_i(new_len, result.size); if (new_len) cl_assert(memcmp(new, result.ptr, new_len) == 0); cl_assert_equal_s(filename_expected, filename); cl_assert_equal_i(mode_expected, mode); } git__free(filename); git_str_dispose(&result); git_str_dispose(&patchbuf); git_patch_free(patch); return error; } static int validate_and_apply_patchfile( const char *old, size_t old_len, const char *new, size_t new_len, const char *patchfile, const git_diff_options *diff_opts, const char *filename_expected, unsigned int mode_expected) { git_patch *patch_fromdiff; git_buf validated = GIT_BUF_INIT; int error; cl_git_pass(git_patch_from_buffers(&patch_fromdiff, old, old_len, "file.txt", new, new_len, "file.txt", diff_opts)); cl_git_pass(git_patch_to_buf(&validated, patch_fromdiff)); cl_assert_equal_s(patchfile, validated.ptr); error = apply_patchfile(old, old_len, new, new_len, patchfile, filename_expected, mode_expected); git_buf_dispose(&validated); git_patch_free(patch_fromdiff); return error; } void test_apply_fromfile__change_middle(void) { cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_MIDDLE, strlen(FILE_CHANGE_MIDDLE), PATCH_ORIGINAL_TO_CHANGE_MIDDLE, NULL, "file.txt", 0100644)); } void test_apply_fromfile__change_middle_nocontext(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_MIDDLE, strlen(FILE_CHANGE_MIDDLE), PATCH_ORIGINAL_TO_CHANGE_MIDDLE_NOCONTEXT, &diff_opts, "file.txt", 0100644)); } void test_apply_fromfile__change_firstline(void) { cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_FIRSTLINE, strlen(FILE_CHANGE_FIRSTLINE), PATCH_ORIGINAL_TO_CHANGE_FIRSTLINE, NULL, "file.txt", 0100644)); } void test_apply_fromfile__lastline(void) { cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_LASTLINE, strlen(FILE_CHANGE_LASTLINE), PATCH_ORIGINAL_TO_CHANGE_LASTLINE, NULL, "file.txt", 0100644)); } void test_apply_fromfile__change_middle_shrink(void) { cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_MIDDLE_SHRINK, strlen(FILE_CHANGE_MIDDLE_SHRINK), PATCH_ORIGINAL_TO_CHANGE_MIDDLE_SHRINK, NULL, "file.txt", 0100644)); } void test_apply_fromfile__change_middle_shrink_nocontext(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_MIDDLE_SHRINK, strlen(FILE_CHANGE_MIDDLE_SHRINK), PATCH_ORIGINAL_TO_MIDDLE_SHRINK_NOCONTEXT, &diff_opts, "file.txt", 0100644)); } void test_apply_fromfile__change_middle_grow(void) { cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_MIDDLE_GROW, strlen(FILE_CHANGE_MIDDLE_GROW), PATCH_ORIGINAL_TO_CHANGE_MIDDLE_GROW, NULL, "file.txt", 0100644)); } void test_apply_fromfile__change_middle_grow_nocontext(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_MIDDLE_GROW, strlen(FILE_CHANGE_MIDDLE_GROW), PATCH_ORIGINAL_TO_MIDDLE_GROW_NOCONTEXT, &diff_opts, "file.txt", 0100644)); } void test_apply_fromfile__prepend(void) { cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_PREPEND, strlen(FILE_PREPEND), PATCH_ORIGINAL_TO_PREPEND, NULL, "file.txt", 0100644)); } void test_apply_fromfile__prepend_nocontext(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_PREPEND, strlen(FILE_PREPEND), PATCH_ORIGINAL_TO_PREPEND_NOCONTEXT, &diff_opts, "file.txt", 0100644)); } void test_apply_fromfile__append(void) { cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_APPEND, strlen(FILE_APPEND), PATCH_ORIGINAL_TO_APPEND, NULL, "file.txt", 0100644)); } void test_apply_fromfile__append_nocontext(void) { git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; diff_opts.context_lines = 0; cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_APPEND, strlen(FILE_APPEND), PATCH_ORIGINAL_TO_APPEND_NOCONTEXT, &diff_opts, "file.txt", 0100644)); } void test_apply_fromfile__prepend_and_append(void) { cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_PREPEND_AND_APPEND, strlen(FILE_PREPEND_AND_APPEND), PATCH_ORIGINAL_TO_PREPEND_AND_APPEND, NULL, "file.txt", 0100644)); } void test_apply_fromfile__to_empty_file(void) { cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), "", 0, PATCH_ORIGINAL_TO_EMPTY_FILE, NULL, "file.txt", 0100644)); } void test_apply_fromfile__from_empty_file(void) { cl_git_pass(validate_and_apply_patchfile( "", 0, FILE_ORIGINAL, strlen(FILE_ORIGINAL), PATCH_EMPTY_FILE_TO_ORIGINAL, NULL, "file.txt", 0100644)); } void test_apply_fromfile__add(void) { cl_git_pass(validate_and_apply_patchfile( NULL, 0, FILE_ORIGINAL, strlen(FILE_ORIGINAL), PATCH_ADD_ORIGINAL, NULL, "file.txt", 0100644)); } void test_apply_fromfile__delete(void) { cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), NULL, 0, PATCH_DELETE_ORIGINAL, NULL, NULL, 0)); } void test_apply_fromfile__rename_exact(void) { cl_git_pass(apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_ORIGINAL, strlen(FILE_ORIGINAL), PATCH_RENAME_EXACT, "newfile.txt", 0100644)); } void test_apply_fromfile__rename_similar(void) { cl_git_pass(apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_MIDDLE, strlen(FILE_CHANGE_MIDDLE), PATCH_RENAME_SIMILAR, "newfile.txt", 0100644)); } void test_apply_fromfile__rename_similar_quotedname(void) { cl_git_pass(apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_MIDDLE, strlen(FILE_CHANGE_MIDDLE), PATCH_RENAME_SIMILAR_QUOTEDNAME, "foo\"bar.txt", 0100644)); } void test_apply_fromfile__modechange(void) { cl_git_pass(apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_ORIGINAL, strlen(FILE_ORIGINAL), PATCH_MODECHANGE_UNCHANGED, "file.txt", 0100755)); } void test_apply_fromfile__modechange_with_modification(void) { cl_git_pass(apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_MIDDLE, strlen(FILE_CHANGE_MIDDLE), PATCH_MODECHANGE_MODIFIED, "file.txt", 0100755)); } void test_apply_fromfile__noisy(void) { cl_git_pass(apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_MIDDLE, strlen(FILE_CHANGE_MIDDLE), PATCH_NOISY, "file.txt", 0100644)); } void test_apply_fromfile__noisy_nocontext(void) { cl_git_pass(apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_CHANGE_MIDDLE, strlen(FILE_CHANGE_MIDDLE), PATCH_NOISY_NOCONTEXT, "file.txt", 0100644)); } void test_apply_fromfile__fail_truncated_1(void) { git_patch *patch; cl_git_fail(git_patch_from_buffer(&patch, PATCH_TRUNCATED_1, strlen(PATCH_TRUNCATED_1), NULL)); } void test_apply_fromfile__fail_truncated_2(void) { git_patch *patch; cl_git_fail(git_patch_from_buffer(&patch, PATCH_TRUNCATED_2, strlen(PATCH_TRUNCATED_2), NULL)); } void test_apply_fromfile__fail_truncated_3(void) { git_patch *patch; cl_git_fail(git_patch_from_buffer(&patch, PATCH_TRUNCATED_3, strlen(PATCH_TRUNCATED_3), NULL)); } void test_apply_fromfile__fail_corrupt_githeader(void) { git_patch *patch; cl_git_fail(git_patch_from_buffer(&patch, PATCH_CORRUPT_GIT_HEADER, strlen(PATCH_CORRUPT_GIT_HEADER), NULL)); } void test_apply_fromfile__empty_context(void) { cl_git_pass(apply_patchfile( FILE_EMPTY_CONTEXT_ORIGINAL, strlen(FILE_EMPTY_CONTEXT_ORIGINAL), FILE_EMPTY_CONTEXT_MODIFIED, strlen(FILE_EMPTY_CONTEXT_MODIFIED), PATCH_EMPTY_CONTEXT, "file.txt", 0100644)); } void test_apply_fromfile__append_no_nl(void) { cl_git_pass(validate_and_apply_patchfile( FILE_ORIGINAL, strlen(FILE_ORIGINAL), FILE_APPEND_NO_NL, strlen(FILE_APPEND_NO_NL), PATCH_APPEND_NO_NL, NULL, "file.txt", 0100644)); } void test_apply_fromfile__fail_missing_new_file(void) { git_patch *patch; cl_git_fail(git_patch_from_buffer(&patch, PATCH_CORRUPT_MISSING_NEW_FILE, strlen(PATCH_CORRUPT_MISSING_NEW_FILE), NULL)); } void test_apply_fromfile__fail_missing_old_file(void) { git_patch *patch; cl_git_fail(git_patch_from_buffer(&patch, PATCH_CORRUPT_MISSING_OLD_FILE, strlen(PATCH_CORRUPT_MISSING_OLD_FILE), NULL)); } void test_apply_fromfile__fail_no_changes(void) { git_patch *patch; cl_git_fail(git_patch_from_buffer(&patch, PATCH_CORRUPT_NO_CHANGES, strlen(PATCH_CORRUPT_NO_CHANGES), NULL)); } void test_apply_fromfile__fail_missing_hunk_header(void) { git_patch *patch; cl_git_fail(git_patch_from_buffer(&patch, PATCH_CORRUPT_MISSING_HUNK_HEADER, strlen(PATCH_CORRUPT_MISSING_HUNK_HEADER), NULL)); } void test_apply_fromfile__fail_not_a_patch(void) { git_patch *patch; cl_git_fail(git_patch_from_buffer(&patch, PATCH_NOT_A_PATCH, strlen(PATCH_NOT_A_PATCH), NULL)); } void test_apply_fromfile__binary_add(void) { cl_git_pass(apply_patchfile( NULL, 0, FILE_BINARY_DELTA_MODIFIED, FILE_BINARY_DELTA_MODIFIED_LEN, PATCH_BINARY_ADD, "binary.bin", 0100644)); } void test_apply_fromfile__binary_change_delta(void) { cl_git_pass(apply_patchfile( FILE_BINARY_DELTA_ORIGINAL, FILE_BINARY_DELTA_ORIGINAL_LEN, FILE_BINARY_DELTA_MODIFIED, FILE_BINARY_DELTA_MODIFIED_LEN, PATCH_BINARY_DELTA, "binary.bin", 0100644)); } void test_apply_fromfile__binary_change_literal(void) { cl_git_pass(apply_patchfile( FILE_BINARY_LITERAL_ORIGINAL, FILE_BINARY_LITERAL_ORIGINAL_LEN, FILE_BINARY_LITERAL_MODIFIED, FILE_BINARY_LITERAL_MODIFIED_LEN, PATCH_BINARY_LITERAL, "binary.bin", 0100644)); } void test_apply_fromfile__binary_delete(void) { cl_git_pass(apply_patchfile( FILE_BINARY_DELTA_MODIFIED, FILE_BINARY_DELTA_MODIFIED_LEN, NULL, 0, PATCH_BINARY_DELETE, NULL, 0)); } void test_apply_fromfile__binary_change_does_not_apply(void) { /* try to apply patch backwards, ensure it does not apply */ cl_git_fail(apply_patchfile( FILE_BINARY_DELTA_MODIFIED, FILE_BINARY_DELTA_MODIFIED_LEN, FILE_BINARY_DELTA_ORIGINAL, FILE_BINARY_DELTA_ORIGINAL_LEN, PATCH_BINARY_DELTA, "binary.bin", 0100644)); } void test_apply_fromfile__binary_change_must_be_reversible(void) { cl_git_fail(apply_patchfile( FILE_BINARY_DELTA_MODIFIED, FILE_BINARY_DELTA_MODIFIED_LEN, NULL, 0, PATCH_BINARY_NOT_REVERSIBLE, NULL, 0)); } void test_apply_fromfile__empty_file_not_allowed(void) { git_patch *patch; cl_git_fail(git_patch_from_buffer(&patch, "", 0, NULL)); cl_git_fail(git_patch_from_buffer(&patch, NULL, 0, NULL)); }
libgit2-main
tests/libgit2/apply/fromfile.c
#include "clar_libgit2.h" #include "apply_helpers.h" static git_repository *repo; #define TEST_REPO_PATH "merge-recursive" void test_apply_callbacks__initialize(void) { git_oid oid; git_commit *commit; repo = cl_git_sandbox_init(TEST_REPO_PATH); git_oid__fromstr(&oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &oid)); cl_git_pass(git_reset(repo, (git_object *)commit, GIT_RESET_HARD, NULL)); git_commit_free(commit); } void test_apply_callbacks__cleanup(void) { cl_git_sandbox_cleanup(); } static int delta_abort_cb(const git_diff_delta *delta, void *payload) { GIT_UNUSED(payload); if (!strcmp(delta->old_file.path, "veal.txt")) return -99; return 0; } void test_apply_callbacks__delta_aborts(void) { git_diff *diff; git_apply_options opts = GIT_APPLY_OPTIONS_INIT; opts.delta_cb = delta_abort_cb; cl_git_pass(git_diff_from_buffer(&diff, DIFF_MODIFY_TWO_FILES, strlen(DIFF_MODIFY_TWO_FILES))); cl_git_fail_with(-99, git_apply(repo, diff, GIT_APPLY_LOCATION_INDEX, &opts)); validate_index_unchanged(repo); validate_workdir_unchanged(repo); git_diff_free(diff); } static int delta_skip_cb(const git_diff_delta *delta, void *payload) { GIT_UNUSED(payload); if (!strcmp(delta->old_file.path, "asparagus.txt")) return 1; return 0; } void test_apply_callbacks__delta_can_skip(void) { git_diff *diff; git_apply_options opts = GIT_APPLY_OPTIONS_INIT; struct merge_index_entry workdir_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); opts.delta_cb = delta_skip_cb; cl_git_pass(git_diff_from_buffer(&diff, DIFF_MODIFY_TWO_FILES, strlen(DIFF_MODIFY_TWO_FILES))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, &opts)); validate_index_unchanged(repo); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } static int hunk_skip_odds_cb(const git_diff_hunk *hunk, void *payload) { int *count = (int *)payload; GIT_UNUSED(hunk); return ((*count)++ % 2 == 1); } void test_apply_callbacks__hunk_can_skip(void) { git_diff *diff; git_apply_options opts = GIT_APPLY_OPTIONS_INIT; int count = 0; struct merge_index_entry workdir_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "06f751b6ba4f017ddbf4248015768300268e092a", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); opts.hunk_cb = hunk_skip_odds_cb; opts.payload = &count; cl_git_pass(git_diff_from_buffer(&diff, DIFF_MANY_CHANGES_ONE, strlen(DIFF_MANY_CHANGES_ONE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, &opts)); validate_index_unchanged(repo); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); }
libgit2-main
tests/libgit2/apply/callbacks.c
#include "clar_libgit2.h" #include "apply_helpers.h" static git_repository *repo; #define TEST_REPO_PATH "merge-recursive" void test_apply_workdir__initialize(void) { git_oid oid; git_commit *commit; repo = cl_git_sandbox_init(TEST_REPO_PATH); git_oid__fromstr(&oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &oid)); cl_git_pass(git_reset(repo, (git_object *)commit, GIT_RESET_HARD, NULL)); git_commit_free(commit); } void test_apply_workdir__cleanup(void) { cl_git_sandbox_cleanup(); } void test_apply_workdir__generated_diff(void) { git_oid a_oid, b_oid; git_commit *a_commit, *b_commit; git_tree *a_tree, *b_tree; git_diff *diff; git_diff_options opts = GIT_DIFF_OPTIONS_INIT; struct merge_index_entry workdir_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); git_oid__fromstr(&a_oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1); git_oid__fromstr(&b_oid, "7c7bf85e978f1d18c0566f702d2cb7766b9c8d4f", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&a_commit, repo, &a_oid)); cl_git_pass(git_commit_lookup(&b_commit, repo, &b_oid)); cl_git_pass(git_commit_tree(&a_tree, a_commit)); cl_git_pass(git_commit_tree(&b_tree, b_commit)); cl_git_pass(git_diff_tree_to_tree(&diff, repo, a_tree, b_tree, &opts)); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, NULL)); validate_index_unchanged(repo); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); git_tree_free(a_tree); git_tree_free(b_tree); git_commit_free(a_commit); git_commit_free(b_commit); } void test_apply_workdir__parsed_diff(void) { git_diff *diff; struct merge_index_entry workdir_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_MODIFY_TWO_FILES, strlen(DIFF_MODIFY_TWO_FILES))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, NULL)); validate_index_unchanged(repo); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } void test_apply_workdir__removes_file(void) { git_diff *diff; struct merge_index_entry workdir_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_DELETE_FILE, strlen(DIFF_DELETE_FILE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, NULL)); validate_index_unchanged(repo); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } void test_apply_workdir__adds_file(void) { git_diff *diff; struct merge_index_entry workdir_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "6370543fcfedb3e6516ec53b06158f3687dc1447", 0, "newfile.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_ADD_FILE, strlen(DIFF_ADD_FILE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, NULL)); validate_index_unchanged(repo); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } void test_apply_workdir__modified_index_with_unmodified_workdir_is_ok(void) { git_index *index; git_index_entry idx_entry = {{0}}; git_diff *diff; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry index_expected[] = { { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "veal.txt" } }; size_t index_expected_cnt = sizeof(index_expected) / sizeof(struct merge_index_entry); struct merge_index_entry workdir_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); /* mutate the index and leave the workdir matching HEAD */ cl_git_pass(git_repository_index(&index, repo)); idx_entry.mode = 0100644; idx_entry.path = "veal.txt"; cl_git_pass(git_oid__fromstr(&idx_entry.id, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", GIT_OID_SHA1)); cl_git_pass(git_index_add(index, &idx_entry)); cl_git_pass(git_index_remove(index, "asparagus.txt", 0)); cl_git_pass(git_index_write(index)); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, NULL)); validate_apply_index(repo, index_expected, index_expected_cnt); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_index_free(index); git_diff_free(diff); } void test_apply_workdir__application_failure_leaves_workdir_unmodified(void) { git_diff *diff; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry workdir_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "8684724651336001c5dbce74bed6736d2443958d", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); /* mutate the workdir */ cl_git_rewritefile("merge-recursive/veal.txt", "This is a modification.\n"); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_fail_with(GIT_EAPPLYFAIL, git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, NULL)); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } void test_apply_workdir__keeps_nonconflicting_changes(void) { git_diff *diff; struct merge_index_entry workdir_expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "f75ba05f340c51065cbea2e1fdbfe5fe13144c97", 0, "gravy.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); cl_git_rmfile("merge-recursive/oyster.txt"); cl_git_rewritefile("merge-recursive/gravy.txt", "Hello, world.\n"); cl_git_pass(git_diff_from_buffer(&diff, DIFF_MODIFY_TWO_FILES, strlen(DIFF_MODIFY_TWO_FILES))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, NULL)); validate_index_unchanged(repo); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } void test_apply_workdir__can_apply_nonconflicting_file_changes(void) { git_diff *diff; const char *diff_file = DIFF_MODIFY_TWO_FILES; struct merge_index_entry workdir_expected[] = { { 0100644, "5db1a0fef164cb66cc0c00d35cc5af979ddc1a64", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); /* * Replace the workdir file with a version that is different than * HEAD but such that the patch still applies cleanly. This item * has a new line appended. */ cl_git_append2file("merge-recursive/asparagus.txt", "This line is added in the workdir.\n"); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, NULL)); validate_index_unchanged(repo); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } void test_apply_workdir__change_mode(void) { #ifndef GIT_WIN32 git_diff *diff; const char *diff_file = DIFF_EXECUTABLE_FILE; struct merge_index_entry workdir_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100755, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, diff_file, strlen(diff_file))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, NULL)); validate_index_unchanged(repo); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); #endif } void test_apply_workdir__apply_many_changes_one(void) { git_diff *diff; git_apply_options opts = GIT_APPLY_OPTIONS_INIT; struct merge_index_entry workdir_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "c9d7d5d58088bc91f6e06f17ca3a205091568d3a", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_MANY_CHANGES_ONE, strlen(DIFF_MANY_CHANGES_ONE))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, &opts)); validate_index_unchanged(repo); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); } void test_apply_workdir__apply_many_changes_two(void) { git_diff *diff; git_apply_options opts = GIT_APPLY_OPTIONS_INIT; struct merge_index_entry workdir_expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "6b943d65af6d8db74d747284fa4ca7d716ad5bbb", 0, "veal.txt" }, }; size_t workdir_expected_cnt = sizeof(workdir_expected) / sizeof(struct merge_index_entry); cl_git_pass(git_diff_from_buffer(&diff, DIFF_MANY_CHANGES_TWO, strlen(DIFF_MANY_CHANGES_TWO))); cl_git_pass(git_apply(repo, diff, GIT_APPLY_LOCATION_WORKDIR, &opts)); validate_index_unchanged(repo); validate_apply_workdir(repo, workdir_expected, workdir_expected_cnt); git_diff_free(diff); }
libgit2-main
tests/libgit2/apply/workdir.c
#include "clar_libgit2.h" #include "apply_helpers.h" #include "../merge/merge_helpers.h" static git_repository *repo; #define TEST_REPO_PATH "merge-recursive" void test_apply_tree__initialize(void) { repo = cl_git_sandbox_init(TEST_REPO_PATH); } void test_apply_tree__cleanup(void) { cl_git_sandbox_cleanup(); } void test_apply_tree__one(void) { git_oid a_oid, b_oid; git_commit *a_commit, *b_commit; git_tree *a_tree, *b_tree; git_diff *diff; git_index *index = NULL; git_diff_options opts = GIT_DIFF_OPTIONS_INIT; struct merge_index_entry expected[] = { { 0100644, "ffb36e513f5fdf8a6ba850a20142676a2ac4807d", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "a7b066537e6be7109abfe4ff97b675d4e077da20", 0, "veal.txt" }, }; git_oid__fromstr(&a_oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1); git_oid__fromstr(&b_oid, "7c7bf85e978f1d18c0566f702d2cb7766b9c8d4f", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&a_commit, repo, &a_oid)); cl_git_pass(git_commit_lookup(&b_commit, repo, &b_oid)); cl_git_pass(git_commit_tree(&a_tree, a_commit)); cl_git_pass(git_commit_tree(&b_tree, b_commit)); cl_git_pass(git_diff_tree_to_tree(&diff, repo, a_tree, b_tree, &opts)); cl_git_pass(git_apply_to_tree(&index, repo, a_tree, diff, NULL)); merge_test_index(index, expected, 6); git_index_free(index); git_diff_free(diff); git_tree_free(a_tree); git_tree_free(b_tree); git_commit_free(a_commit); git_commit_free(b_commit); } void test_apply_tree__adds_file(void) { git_oid a_oid; git_commit *a_commit; git_tree *a_tree; git_diff *diff; git_index *index = NULL; struct merge_index_entry expected[] = { { 0100644, "f51658077d85f2264fa179b4d0848268cb3475c3", 0, "asparagus.txt" }, { 0100644, "68f6182f4c85d39e1309d97c7e456156dc9c0096", 0, "beef.txt" }, { 0100644, "4b7c5650008b2e747fe1809eeb5a1dde0e80850a", 0, "bouilli.txt" }, { 0100644, "c4e6cca3ec6ae0148ed231f97257df8c311e015f", 0, "gravy.txt" }, { 0100644, "6370543fcfedb3e6516ec53b06158f3687dc1447", 0, "newfile.txt" }, { 0100644, "68af1fc7407fd9addf1701a87eb1c95c7494c598", 0, "oyster.txt" }, { 0100644, "94d2c01087f48213bd157222d54edfefd77c9bba", 0, "veal.txt" }, }; git_oid__fromstr(&a_oid, "539bd011c4822c560c1d17cab095006b7a10f707", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&a_commit, repo, &a_oid)); cl_git_pass(git_commit_tree(&a_tree, a_commit)); cl_git_pass(git_diff_from_buffer(&diff, DIFF_ADD_FILE, strlen(DIFF_ADD_FILE))); cl_git_pass(git_apply_to_tree(&index, repo, a_tree, diff, NULL)); merge_test_index(index, expected, 7); git_index_free(index); git_diff_free(diff); git_tree_free(a_tree); git_commit_free(a_commit); }
libgit2-main
tests/libgit2/apply/tree.c
#include "clar_libgit2.h" #include "path.h" #include "util.h" #include "posix.h" #include "submodule_helpers.h" #include "git2/sys/repository.h" /* rewrite gitmodules -> .gitmodules * rewrite the empty or relative urls inside each module * rename the .gitted directory inside any submodule to .git */ void rewrite_gitmodules(const char *workdir) { git_str in_f = GIT_STR_INIT, out_f = GIT_STR_INIT, path = GIT_STR_INIT; FILE *in, *out; char line[256]; cl_git_pass(git_str_joinpath(&in_f, workdir, "gitmodules")); cl_git_pass(git_str_joinpath(&out_f, workdir, ".gitmodules")); cl_assert((in = fopen(in_f.ptr, "rb")) != NULL); cl_assert((out = fopen(out_f.ptr, "wb")) != NULL); while (fgets(line, sizeof(line), in) != NULL) { char *scan = line; while (*scan == ' ' || *scan == '\t') scan++; /* rename .gitted -> .git in submodule directories */ if (git__prefixcmp(scan, "path =") == 0) { scan += strlen("path ="); while (*scan == ' ') scan++; git_str_joinpath(&path, workdir, scan); git_str_rtrim(&path); git_str_joinpath(&path, path.ptr, ".gitted"); if (!git_str_oom(&path) && p_access(path.ptr, F_OK) == 0) { git_str_joinpath(&out_f, workdir, scan); git_str_rtrim(&out_f); git_str_joinpath(&out_f, out_f.ptr, ".git"); if (!git_str_oom(&out_f)) p_rename(path.ptr, out_f.ptr); } } /* copy non-"url =" lines verbatim */ if (git__prefixcmp(scan, "url =") != 0) { fputs(line, out); continue; } /* convert relative URLs in "url =" lines */ scan += strlen("url ="); while (*scan == ' ') scan++; if (*scan == '.') { git_str_joinpath(&path, workdir, scan); git_str_rtrim(&path); } else if (!*scan || *scan == '\n') { git_str_joinpath(&path, workdir, "../testrepo.git"); } else { fputs(line, out); continue; } git_fs_path_prettify(&path, path.ptr, NULL); git_str_putc(&path, '\n'); cl_assert(!git_str_oom(&path)); fwrite(line, scan - line, sizeof(char), out); fputs(path.ptr, out); } fclose(in); fclose(out); cl_must_pass(p_unlink(in_f.ptr)); git_str_dispose(&in_f); git_str_dispose(&out_f); git_str_dispose(&path); } static void cleanup_fixture_submodules(void *payload) { cl_git_sandbox_cleanup(); /* either "submodules" or "submod2" */ if (payload) cl_fixture_cleanup(payload); } git_repository *setup_fixture_submodules(void) { git_repository *repo = cl_git_sandbox_init("submodules"); cl_fixture_sandbox("testrepo.git"); rewrite_gitmodules(git_repository_workdir(repo)); p_rename("submodules/testrepo/.gitted", "submodules/testrepo/.git"); cl_set_cleanup(cleanup_fixture_submodules, "testrepo.git"); cl_git_pass(git_repository_reinit_filesystem(repo, 1)); return repo; } git_repository *setup_fixture_submod2(void) { git_repository *repo = cl_git_sandbox_init("submod2"); cl_fixture_sandbox("submod2_target"); p_rename("submod2_target/.gitted", "submod2_target/.git"); rewrite_gitmodules(git_repository_workdir(repo)); p_rename("submod2/not-submodule/.gitted", "submod2/not-submodule/.git"); p_rename("submod2/not/.gitted", "submod2/not/.git"); cl_set_cleanup(cleanup_fixture_submodules, "submod2_target"); cl_git_pass(git_repository_reinit_filesystem(repo, 1)); return repo; } git_repository *setup_fixture_submod3(void) { git_repository *repo = cl_git_sandbox_init("submod3"); cl_fixture_sandbox("submod2_target"); p_rename("submod2_target/.gitted", "submod2_target/.git"); rewrite_gitmodules(git_repository_workdir(repo)); p_rename("submod3/One/.gitted", "submod3/One/.git"); p_rename("submod3/TWO/.gitted", "submod3/TWO/.git"); p_rename("submod3/three/.gitted", "submod3/three/.git"); p_rename("submod3/FoUr/.gitted", "submod3/FoUr/.git"); p_rename("submod3/Five/.gitted", "submod3/Five/.git"); p_rename("submod3/six/.gitted", "submod3/six/.git"); p_rename("submod3/sEvEn/.gitted", "submod3/sEvEn/.git"); p_rename("submod3/EIGHT/.gitted", "submod3/EIGHT/.git"); p_rename("submod3/nine/.gitted", "submod3/nine/.git"); p_rename("submod3/TEN/.gitted", "submod3/TEN/.git"); cl_set_cleanup(cleanup_fixture_submodules, "submod2_target"); cl_git_pass(git_repository_reinit_filesystem(repo, 1)); return repo; } git_repository *setup_fixture_super(void) { git_repository *repo = cl_git_sandbox_init("super"); cl_fixture_sandbox("sub.git"); p_mkdir("super/sub", 0777); rewrite_gitmodules(git_repository_workdir(repo)); cl_set_cleanup(cleanup_fixture_submodules, "sub.git"); cl_git_pass(git_repository_reinit_filesystem(repo, 1)); return repo; } git_repository *setup_fixture_submodule_simple(void) { git_repository *repo = cl_git_sandbox_init("submodule_simple"); cl_fixture_sandbox("testrepo.git"); p_mkdir("submodule_simple/testrepo", 0777); cl_set_cleanup(cleanup_fixture_submodules, "testrepo.git"); cl_git_pass(git_repository_reinit_filesystem(repo, 1)); return repo; } git_repository *setup_fixture_submodule_with_path(void) { git_repository *repo = cl_git_sandbox_init("submodule_with_path"); cl_fixture_sandbox("testrepo.git"); p_mkdir("submodule_with_path/lib", 0777); p_mkdir("submodule_with_path/lib/testrepo", 0777); cl_set_cleanup(cleanup_fixture_submodules, "testrepo.git"); cl_git_pass(git_repository_reinit_filesystem(repo, 1)); return repo; } void assert__submodule_exists( git_repository *repo, const char *name, const char *msg, const char *file, const char *func, int line) { git_submodule *sm; int error = git_submodule_lookup(&sm, repo, name); if (error) cl_git_report_failure(error, 0, file, func, line, msg); cl_assert_at_line(sm != NULL, file, func, line); git_submodule_free(sm); } void refute__submodule_exists( git_repository *repo, const char *name, int expected_error, const char *msg, const char *file, const char *func, int line) { clar__assert_equal( file, func, line, msg, 1, "%i", expected_error, (int)(git_submodule_lookup(NULL, repo, name))); } unsigned int get_submodule_status(git_repository *repo, const char *name) { unsigned int status = 0; assert(repo && name); cl_git_pass(git_submodule_status(&status, repo, name, GIT_SUBMODULE_IGNORE_UNSPECIFIED)); return status; } static int print_submodules(git_submodule *sm, const char *name, void *p) { unsigned int loc = 0; GIT_UNUSED(p); git_submodule_location(&loc, sm); fprintf(stderr, "# submodule %s (at %s) flags %x\n", name, git_submodule_path(sm), loc); return 0; } void dump_submodules(git_repository *repo) { git_submodule_foreach(repo, print_submodules, NULL); }
libgit2-main
tests/libgit2/submodule/submodule_helpers.c
#include "clar_libgit2.h" #include "submodule_helpers.h" #include "git2/sys/repository.h" #include "repository.h" #include "futils.h" static git_repository *g_repo = NULL; void test_submodule_lookup__initialize(void) { g_repo = setup_fixture_submod2(); } void test_submodule_lookup__cleanup(void) { cl_git_sandbox_cleanup(); } void test_submodule_lookup__simple_lookup(void) { assert_submodule_exists(g_repo, "sm_unchanged"); /* lookup pending change in .gitmodules that is not in HEAD */ assert_submodule_exists(g_repo, "sm_added_and_uncommited"); /* lookup pending change in .gitmodules that is not in HEAD nor index */ assert_submodule_exists(g_repo, "sm_gitmodules_only"); /* lookup git repo subdir that is not added as submodule */ refute_submodule_exists(g_repo, "not-submodule", GIT_EEXISTS); /* lookup existing directory that is not a submodule */ refute_submodule_exists(g_repo, "just_a_dir", GIT_ENOTFOUND); /* lookup existing file that is not a submodule */ refute_submodule_exists(g_repo, "just_a_file", GIT_ENOTFOUND); /* lookup non-existent item */ refute_submodule_exists(g_repo, "no_such_file", GIT_ENOTFOUND); /* lookup a submodule by path with a trailing slash */ assert_submodule_exists(g_repo, "sm_added_and_uncommited/"); } void test_submodule_lookup__can_be_dupped(void) { git_submodule *sm; git_submodule *sm_duplicate; const char *oid = "480095882d281ed676fe5b863569520e54a7d5c0"; /* Check original */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_assert(git_submodule_owner(sm) == g_repo); cl_assert_equal_s("sm_unchanged", git_submodule_name(sm)); cl_assert(git__suffixcmp(git_submodule_path(sm), "sm_unchanged") == 0); cl_assert(git__suffixcmp(git_submodule_url(sm), "/submod2_target") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), oid) == 0); cl_assert(git_oid_streq(git_submodule_head_id(sm), oid) == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), oid) == 0); cl_assert(git_submodule_ignore(sm) == GIT_SUBMODULE_IGNORE_NONE); cl_assert(git_submodule_update_strategy(sm) == GIT_SUBMODULE_UPDATE_CHECKOUT); /* Duplicate and free original */ cl_assert(git_submodule_dup(&sm_duplicate, sm) == 0); git_submodule_free(sm); /* Check duplicate */ cl_assert(git_submodule_owner(sm_duplicate) == g_repo); cl_assert_equal_s("sm_unchanged", git_submodule_name(sm_duplicate)); cl_assert(git__suffixcmp(git_submodule_path(sm_duplicate), "sm_unchanged") == 0); cl_assert(git__suffixcmp(git_submodule_url(sm_duplicate), "/submod2_target") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm_duplicate), oid) == 0); cl_assert(git_oid_streq(git_submodule_head_id(sm_duplicate), oid) == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm_duplicate), oid) == 0); cl_assert(git_submodule_ignore(sm_duplicate) == GIT_SUBMODULE_IGNORE_NONE); cl_assert(git_submodule_update_strategy(sm_duplicate) == GIT_SUBMODULE_UPDATE_CHECKOUT); git_submodule_free(sm_duplicate); } void test_submodule_lookup__accessors(void) { git_submodule *sm; const char *oid = "480095882d281ed676fe5b863569520e54a7d5c0"; cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_assert(git_submodule_owner(sm) == g_repo); cl_assert_equal_s("sm_unchanged", git_submodule_name(sm)); cl_assert(git__suffixcmp(git_submodule_path(sm), "sm_unchanged") == 0); cl_assert(git__suffixcmp(git_submodule_url(sm), "/submod2_target") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), oid) == 0); cl_assert(git_oid_streq(git_submodule_head_id(sm), oid) == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), oid) == 0); cl_assert(git_submodule_ignore(sm) == GIT_SUBMODULE_IGNORE_NONE); cl_assert(git_submodule_update_strategy(sm) == GIT_SUBMODULE_UPDATE_CHECKOUT); git_submodule_free(sm); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_assert_equal_s("sm_changed_head", git_submodule_name(sm)); cl_assert(git_oid_streq(git_submodule_index_id(sm), oid) == 0); cl_assert(git_oid_streq(git_submodule_head_id(sm), oid) == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "3d9386c507f6b093471a3e324085657a3c2b4247") == 0); git_submodule_free(sm); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_added_and_uncommited")); cl_assert_equal_s("sm_added_and_uncommited", git_submodule_name(sm)); cl_assert(git_oid_streq(git_submodule_index_id(sm), oid) == 0); cl_assert(git_submodule_head_id(sm) == NULL); cl_assert(git_oid_streq(git_submodule_wd_id(sm), oid) == 0); git_submodule_free(sm); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_missing_commits")); cl_assert_equal_s("sm_missing_commits", git_submodule_name(sm)); cl_assert(git_oid_streq(git_submodule_index_id(sm), oid) == 0); cl_assert(git_oid_streq(git_submodule_head_id(sm), oid) == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "5e4963595a9774b90524d35a807169049de8ccad") == 0); git_submodule_free(sm); } typedef struct { int count; } sm_lookup_data; static int sm_lookup_cb(git_submodule *sm, const char *name, void *payload) { sm_lookup_data *data = payload; data->count += 1; cl_assert_equal_s(git_submodule_name(sm), name); return 0; } void test_submodule_lookup__foreach(void) { git_config *cfg; sm_lookup_data data; memset(&data, 0, sizeof(data)); cl_git_pass(git_submodule_foreach(g_repo, sm_lookup_cb, &data)); cl_assert_equal_i(8, data.count); memset(&data, 0, sizeof(data)); /* Change the path for a submodule so it doesn't match the name */ cl_git_pass(git_config_open_ondisk(&cfg, "submod2/.gitmodules")); cl_git_pass(git_config_set_string(cfg, "submodule.smchangedindex.path", "sm_changed_index")); cl_git_pass(git_config_set_string(cfg, "submodule.smchangedindex.url", "../submod2_target")); cl_git_pass(git_config_delete_entry(cfg, "submodule.sm_changed_index.path")); cl_git_pass(git_config_delete_entry(cfg, "submodule.sm_changed_index.url")); git_config_free(cfg); cl_git_pass(git_submodule_foreach(g_repo, sm_lookup_cb, &data)); cl_assert_equal_i(8, data.count); } static int foreach_cb(git_submodule *sm, const char *name, void *payload) { GIT_UNUSED(sm); GIT_UNUSED(name); GIT_UNUSED(payload); return 0; } void test_submodule_lookup__duplicated_path(void) { cl_git_rewritefile("submod2/.gitmodules", "[submodule \"sm1\"]\n" " path = duplicated-path\n" " url = sm1\n" "[submodule \"sm2\"]\n" " path = duplicated-path\n" " url = sm2\n"); cl_git_fail(git_submodule_foreach(g_repo, foreach_cb, NULL)); } void test_submodule_lookup__lookup_even_with_unborn_head(void) { git_reference *head; /* put us on an unborn branch */ cl_git_pass(git_reference_symbolic_create( &head, g_repo, "HEAD", "refs/heads/garbage", 1, NULL)); git_reference_free(head); test_submodule_lookup__simple_lookup(); /* baseline should still pass */ } void test_submodule_lookup__lookup_even_with_missing_index(void) { git_index *idx; /* give the repo an empty index */ cl_git_pass(git_index_new(&idx)); git_repository_set_index(g_repo, idx); git_index_free(idx); test_submodule_lookup__simple_lookup(); /* baseline should still pass */ } void test_submodule_lookup__backslashes(void) { git_config *cfg; git_submodule *sm; git_repository *subrepo; git_buf buf = GIT_BUF_INIT; const char *backslashed_path = "..\\submod2_target"; cl_git_pass(git_config_open_ondisk(&cfg, "submod2/.gitmodules")); cl_git_pass(git_config_set_string(cfg, "submodule.sm_unchanged.url", backslashed_path)); git_config_free(cfg); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_assert_equal_s(backslashed_path, git_submodule_url(sm)); cl_git_pass(git_submodule_open(&subrepo, sm)); cl_git_pass(git_submodule_resolve_url(&buf, g_repo, backslashed_path)); git_buf_dispose(&buf); git_submodule_free(sm); git_repository_free(subrepo); } static void baseline_tests(void) { /* small baseline that should work even if we change the index or make * commits from the index */ assert_submodule_exists(g_repo, "sm_unchanged"); assert_submodule_exists(g_repo, "sm_gitmodules_only"); refute_submodule_exists(g_repo, "not-submodule", GIT_EEXISTS); } static void add_submodule_with_commit(const char *name) { git_submodule *sm; git_repository *smrepo; git_index *idx; git_str p = GIT_STR_INIT; cl_git_pass(git_submodule_add_setup(&sm, g_repo, "https://github.com/libgit2/libgit2.git", name, 1)); assert_submodule_exists(g_repo, name); cl_git_pass(git_submodule_open(&smrepo, sm)); cl_git_pass(git_repository_index(&idx, smrepo)); cl_git_pass(git_str_joinpath(&p, git_repository_workdir(smrepo), "file")); cl_git_mkfile(p.ptr, "new file"); git_str_dispose(&p); cl_git_pass(git_index_add_bypath(idx, "file")); cl_git_pass(git_index_write(idx)); git_index_free(idx); cl_repo_commit_from_index(NULL, smrepo, NULL, 0, "initial commit"); git_repository_free(smrepo); cl_git_pass(git_submodule_add_finalize(sm)); git_submodule_free(sm); } void test_submodule_lookup__just_added(void) { git_submodule *sm; git_str snap1 = GIT_STR_INIT, snap2 = GIT_STR_INIT; git_reference *original_head = NULL; refute_submodule_exists(g_repo, "sm_just_added", GIT_ENOTFOUND); refute_submodule_exists(g_repo, "sm_just_added_2", GIT_ENOTFOUND); refute_submodule_exists(g_repo, "sm_just_added_idx", GIT_ENOTFOUND); refute_submodule_exists(g_repo, "sm_just_added_head", GIT_ENOTFOUND); refute_submodule_exists(g_repo, "mismatch_name", GIT_ENOTFOUND); refute_submodule_exists(g_repo, "mismatch_path", GIT_ENOTFOUND); baseline_tests(); cl_git_pass(git_futils_readbuffer(&snap1, "submod2/.gitmodules")); cl_git_pass(git_repository_head(&original_head, g_repo)); cl_git_pass(git_submodule_add_setup(&sm, g_repo, "https://github.com/libgit2/libgit2.git", "sm_just_added", 1)); git_submodule_free(sm); assert_submodule_exists(g_repo, "sm_just_added"); cl_git_pass(git_submodule_add_setup(&sm, g_repo, "https://github.com/libgit2/libgit2.git", "sm_just_added_2", 1)); assert_submodule_exists(g_repo, "sm_just_added_2"); cl_git_fail(git_submodule_add_finalize(sm)); /* fails if no HEAD */ git_submodule_free(sm); add_submodule_with_commit("sm_just_added_head"); cl_repo_commit_from_index(NULL, g_repo, NULL, 0, "commit new sm to head"); assert_submodule_exists(g_repo, "sm_just_added_head"); add_submodule_with_commit("sm_just_added_idx"); assert_submodule_exists(g_repo, "sm_just_added_idx"); cl_git_pass(git_futils_readbuffer(&snap2, "submod2/.gitmodules")); cl_git_append2file( "submod2/.gitmodules", "\n[submodule \"mismatch_name\"]\n" "\tpath = mismatch_path\n" "\turl = https://example.com/example.git\n\n"); assert_submodule_exists(g_repo, "mismatch_name"); assert_submodule_exists(g_repo, "mismatch_path"); assert_submodule_exists(g_repo, "sm_just_added"); assert_submodule_exists(g_repo, "sm_just_added_2"); assert_submodule_exists(g_repo, "sm_just_added_idx"); assert_submodule_exists(g_repo, "sm_just_added_head"); baseline_tests(); cl_git_rewritefile("submod2/.gitmodules", snap2.ptr); git_str_dispose(&snap2); refute_submodule_exists(g_repo, "mismatch_name", GIT_ENOTFOUND); refute_submodule_exists(g_repo, "mismatch_path", GIT_ENOTFOUND); assert_submodule_exists(g_repo, "sm_just_added"); assert_submodule_exists(g_repo, "sm_just_added_2"); assert_submodule_exists(g_repo, "sm_just_added_idx"); assert_submodule_exists(g_repo, "sm_just_added_head"); baseline_tests(); cl_git_rewritefile("submod2/.gitmodules", snap1.ptr); git_str_dispose(&snap1); refute_submodule_exists(g_repo, "mismatch_name", GIT_ENOTFOUND); refute_submodule_exists(g_repo, "mismatch_path", GIT_ENOTFOUND); /* note error code change, because add_setup made a repo in the workdir */ refute_submodule_exists(g_repo, "sm_just_added", GIT_EEXISTS); refute_submodule_exists(g_repo, "sm_just_added_2", GIT_EEXISTS); /* these still exist in index and head respectively */ assert_submodule_exists(g_repo, "sm_just_added_idx"); assert_submodule_exists(g_repo, "sm_just_added_head"); baseline_tests(); { git_index *idx; cl_git_pass(git_repository_index(&idx, g_repo)); cl_git_pass(git_index_remove_bypath(idx, "sm_just_added_idx")); cl_git_pass(git_index_remove_bypath(idx, "sm_just_added_head")); cl_git_pass(git_index_write(idx)); git_index_free(idx); } refute_submodule_exists(g_repo, "sm_just_added_idx", GIT_EEXISTS); assert_submodule_exists(g_repo, "sm_just_added_head"); { cl_git_pass(git_reference_create(NULL, g_repo, "refs/heads/master", git_reference_target(original_head), 1, "move head back")); git_reference_free(original_head); } refute_submodule_exists(g_repo, "sm_just_added_head", GIT_EEXISTS); } /* Test_App and Test_App2 are fairly similar names, make sure we load the right one */ void test_submodule_lookup__prefix_name(void) { git_submodule *sm; cl_git_rewritefile("submod2/.gitmodules", "[submodule \"Test_App\"]\n" " path = Test_App\n" " url = ../Test_App\n" "[submodule \"Test_App2\"]\n" " path = Test_App2\n" " url = ../Test_App\n"); cl_git_pass(git_submodule_lookup(&sm, g_repo, "Test_App")); cl_assert_equal_s("Test_App", git_submodule_name(sm)); git_submodule_free(sm); cl_git_pass(git_submodule_lookup(&sm, g_repo, "Test_App2")); cl_assert_equal_s("Test_App2", git_submodule_name(sm)); git_submodule_free(sm); } void test_submodule_lookup__renamed(void) { const char *newpath = "sm_actually_changed"; git_index *idx; sm_lookup_data data; cl_git_pass(git_repository_index__weakptr(&idx, g_repo)); /* We're replicating 'git mv sm_unchanged sm_actually_changed' in this test */ cl_git_pass(p_rename("submod2/sm_unchanged", "submod2/sm_actually_changed")); /* Change the path in .gitmodules and stage it*/ { git_config *cfg; cl_git_pass(git_config_open_ondisk(&cfg, "submod2/.gitmodules")); cl_git_pass(git_config_set_string(cfg, "submodule.sm_unchanged.path", newpath)); git_config_free(cfg); cl_git_pass(git_index_add_bypath(idx, ".gitmodules")); } /* Change the worktree info in the submodule's config */ { git_config *cfg; cl_git_pass(git_config_open_ondisk(&cfg, "submod2/.git/modules/sm_unchanged/config")); cl_git_pass(git_config_set_string(cfg, "core.worktree", "../../../sm_actually_changed")); git_config_free(cfg); } /* Rename the entry in the index */ { const git_index_entry *e; git_index_entry entry = {{ 0 }}; e = git_index_get_bypath(idx, "sm_unchanged", 0); cl_assert(e); cl_assert_equal_i(GIT_FILEMODE_COMMIT, e->mode); entry.path = newpath; entry.mode = GIT_FILEMODE_COMMIT; git_oid_cpy(&entry.id, &e->id); cl_git_pass(git_index_remove(idx, "sm_unchanged", 0)); cl_git_pass(git_index_add(idx, &entry)); cl_git_pass(git_index_write(idx)); } memset(&data, 0, sizeof(data)); cl_git_pass(git_submodule_foreach(g_repo, sm_lookup_cb, &data)); cl_assert_equal_i(8, data.count); } void test_submodule_lookup__cached(void) { git_submodule *sm; git_submodule *sm2; /* See that the simple tests still pass. */ git_repository_submodule_cache_all(g_repo); test_submodule_lookup__simple_lookup(); git_repository_submodule_cache_clear(g_repo); test_submodule_lookup__simple_lookup(); /* Check that subsequent calls return different objects when cached. */ git_repository_submodule_cache_all(g_repo); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_git_pass(git_submodule_lookup(&sm2, g_repo, "sm_unchanged")); cl_assert_equal_p(sm, sm2); git_submodule_free(sm2); /* and that we get new objects again after clearing the cache. */ git_repository_submodule_cache_clear(g_repo); cl_git_pass(git_submodule_lookup(&sm2, g_repo, "sm_unchanged")); cl_assert(sm != sm2); git_submodule_free(sm); git_submodule_free(sm2); } void test_submodule_lookup__lookup_in_bare_repository_fails(void) { git_submodule *sm; cl_git_sandbox_cleanup(); g_repo = cl_git_sandbox_init("submodules.git"); cl_git_fail(git_submodule_lookup(&sm, g_repo, "nonexisting")); } void test_submodule_lookup__foreach_in_bare_repository_fails(void) { cl_git_sandbox_cleanup(); g_repo = cl_git_sandbox_init("submodules.git"); cl_git_fail(git_submodule_foreach(g_repo, foreach_cb, NULL)); } void test_submodule_lookup__fail_invalid_gitmodules(void) { git_submodule *sm; sm_lookup_data data; memset(&data, 0, sizeof(data)); cl_git_rewritefile("submod2/.gitmodules", "[submodule \"Test_App\"\n" " path = Test_App\n" " url = ../Test_App\n"); cl_git_fail(git_submodule_lookup(&sm, g_repo, "Test_App")); cl_git_fail(git_submodule_foreach(g_repo, sm_lookup_cb, &data)); }
libgit2-main
tests/libgit2/submodule/lookup.c
#include "clar_libgit2.h" #include "posix.h" #include "path.h" #include "submodule_helpers.h" #include "futils.h" #include "repository.h" static git_repository *g_repo = NULL; void test_submodule_escape__cleanup(void) { cl_git_sandbox_cleanup(); } #define EVIL_SM_NAME "../../modules/evil" #define EVIL_SM_NAME_WINDOWS "..\\\\..\\\\modules\\\\evil" #define EVIL_SM_NAME_WINDOWS_UNESC "..\\..\\modules\\evil" static int find_evil(git_submodule *sm, const char *name, void *payload) { int *foundit = (int *) payload; GIT_UNUSED(sm); if (!git__strcmp(EVIL_SM_NAME, name) || !git__strcmp(EVIL_SM_NAME_WINDOWS_UNESC, name)) *foundit = true; return 0; } void test_submodule_escape__from_gitdir(void) { int foundit; git_submodule *sm; git_str buf = GIT_STR_INIT; unsigned int sm_location; g_repo = setup_fixture_submodule_simple(); cl_git_pass(git_str_joinpath(&buf, git_repository_workdir(g_repo), ".gitmodules")); cl_git_rewritefile(buf.ptr, "[submodule \"" EVIL_SM_NAME "\"]\n" " path = testrepo\n" " url = ../testrepo.git\n"); git_str_dispose(&buf); /* Find it all the different ways we know about it */ foundit = 0; cl_git_pass(git_submodule_foreach(g_repo, find_evil, &foundit)); cl_assert_equal_i(0, foundit); cl_git_fail_with(GIT_ENOTFOUND, git_submodule_lookup(&sm, g_repo, EVIL_SM_NAME)); /* * We do know about this as it's in the index and HEAD, but the data is * incomplete as there is no configured data for it (we pretend it * doesn't exist). This leaves us with an odd situation but it's * consistent with what we would do if we did add a submodule with no * configuration. */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); cl_git_pass(git_submodule_location(&sm_location, sm)); cl_assert_equal_i(GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_HEAD, sm_location); git_submodule_free(sm); } void test_submodule_escape__from_gitdir_windows(void) { int foundit; git_submodule *sm; git_str buf = GIT_STR_INIT; unsigned int sm_location; g_repo = setup_fixture_submodule_simple(); cl_git_pass(git_str_joinpath(&buf, git_repository_workdir(g_repo), ".gitmodules")); cl_git_rewritefile(buf.ptr, "[submodule \"" EVIL_SM_NAME_WINDOWS "\"]\n" " path = testrepo\n" " url = ../testrepo.git\n"); git_str_dispose(&buf); /* Find it all the different ways we know about it */ foundit = 0; cl_git_pass(git_submodule_foreach(g_repo, find_evil, &foundit)); cl_assert_equal_i(0, foundit); cl_git_fail_with(GIT_ENOTFOUND, git_submodule_lookup(&sm, g_repo, EVIL_SM_NAME_WINDOWS_UNESC)); /* * We do know about this as it's in the index and HEAD, but the data is * incomplete as there is no configured data for it (we pretend it * doesn't exist). This leaves us with an odd situation but it's * consistent with what we would do if we did add a submodule with no * configuration. */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); cl_git_pass(git_submodule_location(&sm_location, sm)); cl_assert_equal_i(GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_HEAD, sm_location); git_submodule_free(sm); }
libgit2-main
tests/libgit2/submodule/escape.c
/* test the submodule APIs on repositories where there are no submodules */ #include "clar_libgit2.h" #include "posix.h" #include "futils.h" void test_submodule_nosubs__cleanup(void) { cl_git_sandbox_cleanup(); } void test_submodule_nosubs__lookup(void) { git_repository *repo = cl_git_sandbox_init("status"); git_submodule *sm = NULL; p_mkdir("status/subrepo", 0777); cl_git_mkfile("status/subrepo/.git", "gitdir: ../.git"); cl_assert_equal_i(GIT_ENOTFOUND, git_submodule_lookup(&sm, repo, "subdir")); cl_assert_equal_i(GIT_EEXISTS, git_submodule_lookup(&sm, repo, "subrepo")); cl_assert_equal_i(GIT_ENOTFOUND, git_submodule_lookup(&sm, repo, "subdir")); cl_assert_equal_i(GIT_EEXISTS, git_submodule_lookup(&sm, repo, "subrepo")); } static int fake_submod_cb(git_submodule *sm, const char *n, void *p) { GIT_UNUSED(sm); GIT_UNUSED(n); GIT_UNUSED(p); return 0; } void test_submodule_nosubs__foreach(void) { git_repository *repo = cl_git_sandbox_init("status"); cl_git_pass(git_submodule_foreach(repo, fake_submod_cb, NULL)); } void test_submodule_nosubs__add(void) { git_repository *repo = cl_git_sandbox_init("status"); git_submodule *sm, *sm2; cl_git_pass(git_submodule_add_setup(&sm, repo, "https://github.com/libgit2/libgit2.git", "submodules/libgit2", 1)); cl_git_pass(git_submodule_lookup(&sm2, repo, "submodules/libgit2")); git_submodule_free(sm2); cl_git_pass(git_submodule_foreach(repo, fake_submod_cb, NULL)); git_submodule_free(sm); } void test_submodule_nosubs__bad_gitmodules(void) { git_repository *repo = cl_git_sandbox_init("status"); cl_git_mkfile("status/.gitmodules", "[submodule \"foobar\"]\tpath=blargle\n\turl=\n\tbranch=\n\tupdate=flooble\n\n"); cl_git_rewritefile("status/.gitmodules", "[submodule \"foobar\"]\tpath=blargle\n\turl=\n\tbranch=\n\tupdate=rebase\n\n"); cl_git_pass(git_submodule_lookup(NULL, repo, "foobar")); cl_assert_equal_i(GIT_ENOTFOUND, git_submodule_lookup(NULL, repo, "subdir")); } void test_submodule_nosubs__add_and_delete(void) { git_repository *repo = cl_git_sandbox_init("status"); git_submodule *sm; git_str buf = GIT_STR_INIT; cl_git_fail(git_submodule_lookup(NULL, repo, "libgit2")); cl_git_fail(git_submodule_lookup(NULL, repo, "submodules/libgit2")); /* create */ cl_git_pass(git_submodule_add_setup( &sm, repo, "https://github.com/libgit2/libgit2.git", "submodules/libgit2", 1)); cl_assert_equal_s("submodules/libgit2", git_submodule_name(sm)); cl_assert_equal_s("submodules/libgit2", git_submodule_path(sm)); git_submodule_free(sm); cl_git_pass(git_futils_readbuffer(&buf, "status/.gitmodules")); cl_assert(strstr(buf.ptr, "[submodule \"submodules/libgit2\"]") != NULL); cl_assert(strstr(buf.ptr, "path = submodules/libgit2") != NULL); git_str_dispose(&buf); /* lookup */ cl_git_fail(git_submodule_lookup(&sm, repo, "libgit2")); cl_git_pass(git_submodule_lookup(&sm, repo, "submodules/libgit2")); cl_assert_equal_s("submodules/libgit2", git_submodule_name(sm)); cl_assert_equal_s("submodules/libgit2", git_submodule_path(sm)); git_submodule_free(sm); /* update name */ cl_git_rewritefile( "status/.gitmodules", "[submodule \"libgit2\"]\n" " path = submodules/libgit2\n" " url = https://github.com/libgit2/libgit2.git\n"); cl_git_pass(git_submodule_lookup(&sm, repo, "libgit2")); cl_assert_equal_s("libgit2", git_submodule_name(sm)); cl_assert_equal_s("submodules/libgit2", git_submodule_path(sm)); git_submodule_free(sm); cl_git_pass(git_submodule_lookup(&sm, repo, "submodules/libgit2")); git_submodule_free(sm); /* revert name update */ cl_git_rewritefile( "status/.gitmodules", "[submodule \"submodules/libgit2\"]\n" " path = submodules/libgit2\n" " url = https://github.com/libgit2/libgit2.git\n"); cl_git_fail(git_submodule_lookup(&sm, repo, "libgit2")); cl_git_pass(git_submodule_lookup(&sm, repo, "submodules/libgit2")); git_submodule_free(sm); /* remove completely */ cl_must_pass(p_unlink("status/.gitmodules")); cl_git_fail(git_submodule_lookup(&sm, repo, "libgit2")); cl_git_fail(git_submodule_lookup(&sm, repo, "submodules/libgit2")); }
libgit2-main
tests/libgit2/submodule/nosubs.c
#include "clar_libgit2.h" #include "posix.h" #include "path.h" #include "submodule_helpers.h" #include "futils.h" static git_repository *g_repo = NULL; void test_submodule_init__cleanup(void) { cl_git_sandbox_cleanup(); } void test_submodule_init__absolute_url(void) { git_submodule *sm; git_config *cfg; git_str absolute_url = GIT_STR_INIT; const char *config_url; g_repo = setup_fixture_submodule_simple(); cl_assert(git_fs_path_dirname_r(&absolute_url, git_repository_workdir(g_repo)) > 0); cl_git_pass(git_str_joinpath(&absolute_url, absolute_url.ptr, "testrepo.git")); /* write the absolute url to the .gitmodules file*/ cl_git_pass(git_submodule_set_url(g_repo, "testrepo", absolute_url.ptr)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); /* verify that the .gitmodules is set with an absolute path*/ cl_assert_equal_s(absolute_url.ptr, git_submodule_url(sm)); /* init and verify that absolute path is written to .git/config */ cl_git_pass(git_submodule_init(sm, false)); cl_git_pass(git_repository_config_snapshot(&cfg, g_repo)); cl_git_pass(git_config_get_string(&config_url, cfg, "submodule.testrepo.url")); cl_assert_equal_s(absolute_url.ptr, config_url); git_str_dispose(&absolute_url); git_config_free(cfg); git_submodule_free(sm); } void test_submodule_init__relative_url(void) { git_submodule *sm; git_config *cfg; git_str absolute_url = GIT_STR_INIT; const char *config_url; g_repo = setup_fixture_submodule_simple(); cl_assert(git_fs_path_dirname_r(&absolute_url, git_repository_workdir(g_repo)) > 0); cl_git_pass(git_str_joinpath(&absolute_url, absolute_url.ptr, "testrepo.git")); cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); /* verify that the .gitmodules is set with an absolute path*/ cl_assert_equal_s("../testrepo.git", git_submodule_url(sm)); /* init and verify that absolute path is written to .git/config */ cl_git_pass(git_submodule_init(sm, false)); cl_git_pass(git_repository_config_snapshot(&cfg, g_repo)); cl_git_pass(git_config_get_string(&config_url, cfg, "submodule.testrepo.url")); cl_assert_equal_s(absolute_url.ptr, config_url); git_str_dispose(&absolute_url); git_config_free(cfg); git_submodule_free(sm); } void test_submodule_init__relative_url_detached_head(void) { git_submodule *sm; git_config *cfg; git_str absolute_url = GIT_STR_INIT; const char *config_url; git_reference *head_ref = NULL; git_object *head_commit = NULL; g_repo = setup_fixture_submodule_simple(); /* Put the parent repository into a detached head state. */ cl_git_pass(git_repository_head(&head_ref, g_repo)); cl_git_pass(git_reference_peel(&head_commit, head_ref, GIT_OBJECT_COMMIT)); cl_git_pass(git_repository_set_head_detached(g_repo, git_commit_id((git_commit *)head_commit))); cl_assert(git_fs_path_dirname_r(&absolute_url, git_repository_workdir(g_repo)) > 0); cl_git_pass(git_str_joinpath(&absolute_url, absolute_url.ptr, "testrepo.git")); cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); /* verify that the .gitmodules is set with an absolute path*/ cl_assert_equal_s("../testrepo.git", git_submodule_url(sm)); /* init and verify that absolute path is written to .git/config */ cl_git_pass(git_submodule_init(sm, false)); cl_git_pass(git_repository_config_snapshot(&cfg, g_repo)); cl_git_pass(git_config_get_string(&config_url, cfg, "submodule.testrepo.url")); cl_assert_equal_s(absolute_url.ptr, config_url); git_str_dispose(&absolute_url); git_config_free(cfg); git_object_free(head_commit); git_reference_free(head_ref); git_submodule_free(sm); }
libgit2-main
tests/libgit2/submodule/init.c
#include "clar_libgit2.h" #include "posix.h" #include "path.h" #include "submodule_helpers.h" #include "futils.h" static git_repository *g_repo = NULL; void test_submodule_update__cleanup(void) { cl_git_sandbox_cleanup(); } void test_submodule_update__uninitialized_submodule_no_init(void) { git_submodule *sm; git_submodule_update_options update_options = GIT_SUBMODULE_UPDATE_OPTIONS_INIT; g_repo = setup_fixture_submodule_simple(); /* get the submodule */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); /* updating an uninitialized repository throws */ cl_git_fail_with( GIT_ERROR, git_submodule_update(sm, 0, &update_options)); git_submodule_free(sm); } struct update_submodule_cb_payload { int update_tips_called; int checkout_progress_called; int checkout_notify_called; }; static void checkout_progress_cb( const char *path, size_t completed_steps, size_t total_steps, void *payload) { struct update_submodule_cb_payload *update_payload = payload; GIT_UNUSED(path); GIT_UNUSED(completed_steps); GIT_UNUSED(total_steps); update_payload->checkout_progress_called = 1; } static int checkout_notify_cb( git_checkout_notify_t why, const char *path, const git_diff_file *baseline, const git_diff_file *target, const git_diff_file *workdir, void *payload) { struct update_submodule_cb_payload *update_payload = payload; GIT_UNUSED(why); GIT_UNUSED(path); GIT_UNUSED(baseline); GIT_UNUSED(target); GIT_UNUSED(workdir); update_payload->checkout_notify_called = 1; return 0; } static int update_tips(const char *refname, const git_oid *a, const git_oid *b, void *data) { struct update_submodule_cb_payload *update_payload = data; GIT_UNUSED(refname); GIT_UNUSED(a); GIT_UNUSED(b); update_payload->update_tips_called = 1; return 1; } void test_submodule_update__update_submodule(void) { git_submodule *sm; git_submodule_update_options update_options = GIT_SUBMODULE_UPDATE_OPTIONS_INIT; unsigned int submodule_status = 0; struct update_submodule_cb_payload update_payload = { 0 }; g_repo = setup_fixture_submodule_simple(); update_options.checkout_opts.progress_cb = checkout_progress_cb; update_options.checkout_opts.progress_payload = &update_payload; update_options.fetch_opts.callbacks.update_tips = update_tips; update_options.fetch_opts.callbacks.payload = &update_payload; /* get the submodule */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); /* verify the initial state of the submodule */ cl_git_pass(git_submodule_status(&submodule_status, g_repo, "testrepo", GIT_SUBMODULE_IGNORE_UNSPECIFIED)); cl_assert_equal_i(submodule_status, GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_WD_UNINITIALIZED); /* initialize and update the submodule */ cl_git_pass(git_submodule_init(sm, 0)); cl_git_pass(git_submodule_update(sm, 0, &update_options)); /* verify state */ cl_git_pass(git_submodule_status(&submodule_status, g_repo, "testrepo", GIT_SUBMODULE_IGNORE_UNSPECIFIED)); cl_assert_equal_i(submodule_status, GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_IN_WD); cl_assert(git_oid_streq(git_submodule_head_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); /* verify that the expected callbacks have been called. */ cl_assert_equal_i(1, update_payload.checkout_progress_called); cl_assert_equal_i(1, update_payload.update_tips_called); git_submodule_free(sm); } void test_submodule_update__update_submodule_with_path(void) { git_submodule *sm; git_submodule_update_options update_options = GIT_SUBMODULE_UPDATE_OPTIONS_INIT; unsigned int submodule_status = 0; struct update_submodule_cb_payload update_payload = { 0 }; g_repo = setup_fixture_submodule_with_path(); update_options.checkout_opts.progress_cb = checkout_progress_cb; update_options.checkout_opts.progress_payload = &update_payload; update_options.fetch_opts.callbacks.update_tips = update_tips; update_options.fetch_opts.callbacks.payload = &update_payload; /* get the submodule */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); /* verify the initial state of the submodule */ cl_git_pass(git_submodule_status(&submodule_status, g_repo, "testrepo", GIT_SUBMODULE_IGNORE_UNSPECIFIED)); cl_assert_equal_i(submodule_status, GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_WD_UNINITIALIZED); /* initialize and update the submodule */ cl_git_pass(git_submodule_init(sm, 0)); cl_git_pass(git_submodule_update(sm, 0, &update_options)); /* verify state */ cl_git_pass(git_submodule_status(&submodule_status, g_repo, "testrepo", GIT_SUBMODULE_IGNORE_UNSPECIFIED)); cl_assert_equal_i(submodule_status, GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_IN_WD); cl_assert(git_oid_streq(git_submodule_head_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); /* verify that the expected callbacks have been called. */ cl_assert_equal_i(1, update_payload.checkout_progress_called); cl_assert_equal_i(1, update_payload.update_tips_called); git_submodule_free(sm); } void test_submodule_update__update_and_init_submodule(void) { git_submodule *sm; git_submodule_update_options update_options = GIT_SUBMODULE_UPDATE_OPTIONS_INIT; unsigned int submodule_status = 0; g_repo = setup_fixture_submodule_simple(); /* get the submodule */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); cl_git_pass(git_submodule_status(&submodule_status, g_repo, "testrepo", GIT_SUBMODULE_IGNORE_UNSPECIFIED)); cl_assert_equal_i(submodule_status, GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_WD_UNINITIALIZED); /* update (with option to initialize sub repo) */ cl_git_pass(git_submodule_update(sm, 1, &update_options)); /* verify expected state */ cl_assert(git_oid_streq(git_submodule_head_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); git_submodule_free(sm); } void test_submodule_update__update_already_checked_out_submodule(void) { git_submodule *sm = NULL; git_checkout_options checkout_options = GIT_CHECKOUT_OPTIONS_INIT; git_submodule_update_options update_options = GIT_SUBMODULE_UPDATE_OPTIONS_INIT; unsigned int submodule_status = 0; git_reference *branch_reference = NULL; git_object *branch_commit = NULL; struct update_submodule_cb_payload update_payload = { 0 }; g_repo = setup_fixture_submodule_simple(); update_options.checkout_opts.progress_cb = checkout_progress_cb; update_options.checkout_opts.progress_payload = &update_payload; /* Initialize and update the sub repository */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); cl_git_pass(git_submodule_status(&submodule_status, g_repo, "testrepo", GIT_SUBMODULE_IGNORE_UNSPECIFIED)); cl_assert_equal_i(submodule_status, GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_WD_UNINITIALIZED); cl_git_pass(git_submodule_update(sm, 1, &update_options)); /* verify expected state */ cl_assert(git_oid_streq(git_submodule_head_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); /* checkout the alternate_1 branch */ checkout_options.checkout_strategy = GIT_CHECKOUT_SAFE; cl_git_pass(git_reference_lookup(&branch_reference, g_repo, "refs/heads/alternate_1")); cl_git_pass(git_reference_peel(&branch_commit, branch_reference, GIT_OBJECT_COMMIT)); cl_git_pass(git_checkout_tree(g_repo, branch_commit, &checkout_options)); cl_git_pass(git_repository_set_head(g_repo, git_reference_name(branch_reference))); /* * Verify state after checkout of parent repository. The submodule ID in the * HEAD commit and index should be updated, but not the workdir. */ cl_git_pass(git_submodule_status(&submodule_status, g_repo, "testrepo", GIT_SUBMODULE_IGNORE_UNSPECIFIED)); git_submodule_free(sm); cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); cl_assert_equal_i(submodule_status, GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_IN_WD | GIT_SUBMODULE_STATUS_WD_MODIFIED); cl_assert(git_oid_streq(git_submodule_head_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); /* * Update the submodule and verify the state. * Now, the HEAD, index, and Workdir commits should all be updated to * the new commit. */ cl_git_pass(git_submodule_update(sm, 0, &update_options)); cl_assert(git_oid_streq(git_submodule_head_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); /* verify that the expected callbacks have been called. */ cl_assert_equal_i(1, update_payload.checkout_progress_called); git_submodule_free(sm); git_object_free(branch_commit); git_reference_free(branch_reference); } void test_submodule_update__update_blocks_on_dirty_wd(void) { git_submodule *sm = NULL; git_checkout_options checkout_options = GIT_CHECKOUT_OPTIONS_INIT; git_submodule_update_options update_options = GIT_SUBMODULE_UPDATE_OPTIONS_INIT; unsigned int submodule_status = 0; git_reference *branch_reference = NULL; git_object *branch_commit = NULL; struct update_submodule_cb_payload update_payload = { 0 }; g_repo = setup_fixture_submodule_simple(); update_options.checkout_opts.notify_flags = GIT_CHECKOUT_NOTIFY_CONFLICT; update_options.checkout_opts.notify_cb = checkout_notify_cb; update_options.checkout_opts.notify_payload = &update_payload; /* Initialize and update the sub repository */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); cl_git_pass(git_submodule_status(&submodule_status, g_repo, "testrepo", GIT_SUBMODULE_IGNORE_UNSPECIFIED)); cl_assert_equal_i(submodule_status, GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_WD_UNINITIALIZED); cl_git_pass(git_submodule_update(sm, 1, &update_options)); /* verify expected state */ cl_assert(git_oid_streq(git_submodule_head_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); /* checkout the alternate_1 branch */ checkout_options.checkout_strategy = GIT_CHECKOUT_SAFE; cl_git_pass(git_reference_lookup(&branch_reference, g_repo, "refs/heads/alternate_1")); cl_git_pass(git_reference_peel(&branch_commit, branch_reference, GIT_OBJECT_COMMIT)); cl_git_pass(git_checkout_tree(g_repo, branch_commit, &checkout_options)); cl_git_pass(git_repository_set_head(g_repo, git_reference_name(branch_reference))); /* * Verify state after checkout of parent repository. The submodule ID in the * HEAD commit and index should be updated, but not the workdir. */ cl_git_pass(git_submodule_status(&submodule_status, g_repo, "testrepo", GIT_SUBMODULE_IGNORE_UNSPECIFIED)); git_submodule_free(sm); cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); cl_assert_equal_i(submodule_status, GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_IN_WD | GIT_SUBMODULE_STATUS_WD_MODIFIED); cl_assert(git_oid_streq(git_submodule_head_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); /* * Create a conflicting edit in the subrepository to verify that * the submodule update action is blocked. */ cl_git_write2file("submodule_simple/testrepo/branch_file.txt", "a conflicting edit", 0, O_WRONLY | O_CREAT | O_TRUNC, 0755); cl_git_fail(git_submodule_update(sm, 0, &update_options)); /* verify that the expected callbacks have been called. */ cl_assert_equal_i(1, update_payload.checkout_notify_called); /* verify that the submodule state has not changed. */ cl_assert(git_oid_streq(git_submodule_head_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); git_submodule_free(sm); git_object_free(branch_commit); git_reference_free(branch_reference); } void test_submodule_update__can_force_update(void) { git_submodule *sm = NULL; git_checkout_options checkout_options = GIT_CHECKOUT_OPTIONS_INIT; git_submodule_update_options update_options = GIT_SUBMODULE_UPDATE_OPTIONS_INIT; unsigned int submodule_status = 0; git_reference *branch_reference = NULL; git_object *branch_commit = NULL; g_repo = setup_fixture_submodule_simple(); /* Initialize and update the sub repository */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); cl_git_pass(git_submodule_status(&submodule_status, g_repo, "testrepo", GIT_SUBMODULE_IGNORE_UNSPECIFIED)); cl_assert_equal_i(submodule_status, GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_WD_UNINITIALIZED); cl_git_pass(git_submodule_update(sm, 1, &update_options)); /* verify expected state */ cl_assert(git_oid_streq(git_submodule_head_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); /* checkout the alternate_1 branch */ checkout_options.checkout_strategy = GIT_CHECKOUT_SAFE; cl_git_pass(git_reference_lookup(&branch_reference, g_repo, "refs/heads/alternate_1")); cl_git_pass(git_reference_peel(&branch_commit, branch_reference, GIT_OBJECT_COMMIT)); cl_git_pass(git_checkout_tree(g_repo, branch_commit, &checkout_options)); cl_git_pass(git_repository_set_head(g_repo, git_reference_name(branch_reference))); /* * Verify state after checkout of parent repository. The submodule ID in the * HEAD commit and index should be updated, but not the workdir. */ cl_git_pass(git_submodule_status(&submodule_status, g_repo, "testrepo", GIT_SUBMODULE_IGNORE_UNSPECIFIED)); git_submodule_free(sm); cl_git_pass(git_submodule_lookup(&sm, g_repo, "testrepo")); cl_assert_equal_i(submodule_status, GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_IN_WD | GIT_SUBMODULE_STATUS_WD_MODIFIED); cl_assert(git_oid_streq(git_submodule_head_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "be3563ae3f795b2b4353bcce3a527ad0a4f7f644") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); /* * Create a conflicting edit in the subrepository to verify that * the submodule update action is blocked. */ cl_git_write2file("submodule_simple/testrepo/branch_file.txt", "a conflicting edit", 0, O_WRONLY | O_CREAT | O_TRUNC, 0777); /* forcefully checkout and verify the submodule state was updated. */ update_options.checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE; cl_git_pass(git_submodule_update(sm, 0, &update_options)); cl_assert(git_oid_streq(git_submodule_head_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); cl_assert(git_oid_streq(git_submodule_wd_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); cl_assert(git_oid_streq(git_submodule_index_id(sm), "a65fedf39aefe402d3bb6e24df4d4f5fe4547750") == 0); git_submodule_free(sm); git_object_free(branch_commit); git_reference_free(branch_reference); }
libgit2-main
tests/libgit2/submodule/update.c
#include "clar_libgit2.h" #include "posix.h" #include "path.h" #include "submodule_helpers.h" #include "futils.h" #include "repository.h" static git_repository *g_repo = NULL; void test_submodule_inject_option__initialize(void) { g_repo = setup_fixture_submodule_simple(); } void test_submodule_inject_option__cleanup(void) { cl_git_sandbox_cleanup(); } static int find_naughty(git_submodule *sm, const char *name, void *payload) { int *foundit = (int *) payload; GIT_UNUSED(sm); if (!git__strcmp("naughty", name)) *foundit = true; return 0; } void test_submodule_inject_option__url(void) { int foundit; git_submodule *sm; git_str buf = GIT_STR_INIT; cl_git_pass(git_str_joinpath(&buf, git_repository_workdir(g_repo), ".gitmodules")); cl_git_rewritefile(buf.ptr, "[submodule \"naughty\"]\n" " path = testrepo\n" " url = -u./payload\n"); git_str_dispose(&buf); /* We do want to find it, but with the appropriate field empty */ foundit = 0; cl_git_pass(git_submodule_foreach(g_repo, find_naughty, &foundit)); cl_assert_equal_i(1, foundit); cl_git_pass(git_submodule_lookup(&sm, g_repo, "naughty")); cl_assert_equal_s("testrepo", git_submodule_path(sm)); cl_assert_equal_p(NULL, git_submodule_url(sm)); git_submodule_free(sm); } void test_submodule_inject_option__path(void) { int foundit; git_submodule *sm; git_str buf = GIT_STR_INIT; cl_git_pass(git_str_joinpath(&buf, git_repository_workdir(g_repo), ".gitmodules")); cl_git_rewritefile(buf.ptr, "[submodule \"naughty\"]\n" " path = --something\n" " url = blah.git\n"); git_str_dispose(&buf); /* We do want to find it, but with the appropriate field empty */ foundit = 0; cl_git_pass(git_submodule_foreach(g_repo, find_naughty, &foundit)); cl_assert_equal_i(1, foundit); cl_git_pass(git_submodule_lookup(&sm, g_repo, "naughty")); cl_assert_equal_s("naughty", git_submodule_path(sm)); cl_assert_equal_s("blah.git", git_submodule_url(sm)); git_submodule_free(sm); }
libgit2-main
tests/libgit2/submodule/inject_option.c
#include "clar_libgit2.h" #include "posix.h" #include "path.h" #include "submodule_helpers.h" #include "config/config_helpers.h" #include "futils.h" static git_repository *g_repo = NULL; void test_submodule_repository_init__basic(void) { git_submodule *sm; git_repository *repo; git_str dot_git_content = GIT_STR_INIT; g_repo = setup_fixture_submod2(); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_gitmodules_only")); cl_git_pass(git_submodule_init(sm, 0)); cl_git_pass(git_submodule_repo_init(&repo, sm, 1)); /* Verify worktree */ assert_config_entry_value(repo, "core.worktree", "../../../sm_gitmodules_only/"); /* Verify gitlink */ cl_git_pass(git_futils_readbuffer(&dot_git_content, "submod2/" "sm_gitmodules_only" "/.git")); cl_assert_equal_s("gitdir: ../.git/modules/sm_gitmodules_only/", dot_git_content.ptr); cl_assert(git_fs_path_isfile("submod2/" "sm_gitmodules_only" "/.git")); cl_assert(git_fs_path_isdir("submod2/.git/modules")); cl_assert(git_fs_path_isdir("submod2/.git/modules/" "sm_gitmodules_only")); cl_assert(git_fs_path_isfile("submod2/.git/modules/" "sm_gitmodules_only" "/HEAD")); git_submodule_free(sm); git_repository_free(repo); git_str_dispose(&dot_git_content); }
libgit2-main
tests/libgit2/submodule/repository_init.c
#include "clar_libgit2.h" #include "posix.h" #include "path.h" #include "submodule_helpers.h" #include "futils.h" #include "iterator.h" static git_repository *g_repo = NULL; void test_submodule_status__initialize(void) { g_repo = setup_fixture_submod2(); } void test_submodule_status__cleanup(void) { } void test_submodule_status__unchanged(void) { unsigned int status = get_submodule_status(g_repo, "sm_unchanged"); unsigned int expected = GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_IN_WD; cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_assert(expected == status); } static void rm_submodule(const char *name) { git_str path = GIT_STR_INIT; cl_git_pass(git_str_joinpath(&path, git_repository_workdir(g_repo), name)); cl_git_pass(git_futils_rmdir_r(path.ptr, NULL, GIT_RMDIR_REMOVE_FILES)); git_str_dispose(&path); } static void add_submodule_to_index(const char *name) { git_submodule *sm; cl_git_pass(git_submodule_lookup(&sm, g_repo, name)); cl_git_pass(git_submodule_add_to_index(sm, true)); git_submodule_free(sm); } static void rm_submodule_from_index(const char *name) { git_index *index; size_t pos; cl_git_pass(git_repository_index(&index, g_repo)); cl_assert(!git_index_find(&pos, index, name)); cl_git_pass(git_index_remove(index, name, 0)); cl_git_pass(git_index_write(index)); git_index_free(index); } /* 4 values of GIT_SUBMODULE_IGNORE to check */ void test_submodule_status__ignore_none(void) { unsigned int status; rm_submodule("sm_unchanged"); refute_submodule_exists(g_repo, "just_a_dir", GIT_ENOTFOUND); refute_submodule_exists(g_repo, "not-submodule", GIT_EEXISTS); refute_submodule_exists(g_repo, "not", GIT_EEXISTS); status = get_submodule_status(g_repo, "sm_changed_index"); cl_assert((status & GIT_SUBMODULE_STATUS_WD_INDEX_MODIFIED) != 0); status = get_submodule_status(g_repo, "sm_changed_head"); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); status = get_submodule_status(g_repo, "sm_changed_file"); cl_assert((status & GIT_SUBMODULE_STATUS_WD_WD_MODIFIED) != 0); status = get_submodule_status(g_repo, "sm_changed_untracked_file"); cl_assert((status & GIT_SUBMODULE_STATUS_WD_UNTRACKED) != 0); status = get_submodule_status(g_repo, "sm_missing_commits"); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); status = get_submodule_status(g_repo, "sm_added_and_uncommited"); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_ADDED) != 0); /* removed sm_unchanged for deleted workdir */ status = get_submodule_status(g_repo, "sm_unchanged"); cl_assert((status & GIT_SUBMODULE_STATUS_WD_DELETED) != 0); /* now mkdir sm_unchanged to test uninitialized */ cl_git_pass(git_futils_mkdir_relative("sm_unchanged", "submod2", 0755, 0, NULL)); status = get_submodule_status(g_repo, "sm_unchanged"); cl_assert((status & GIT_SUBMODULE_STATUS_WD_UNINITIALIZED) != 0); /* update sm_changed_head in index */ add_submodule_to_index("sm_changed_head"); status = get_submodule_status(g_repo, "sm_changed_head"); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_MODIFIED) != 0); /* remove sm_changed_head from index */ rm_submodule_from_index("sm_changed_head"); status = get_submodule_status(g_repo, "sm_changed_head"); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_DELETED) != 0); } void test_submodule_status__ignore_untracked(void) { unsigned int status; git_submodule_ignore_t ign = GIT_SUBMODULE_IGNORE_UNTRACKED; rm_submodule("sm_unchanged"); refute_submodule_exists(g_repo, "just_a_dir", GIT_ENOTFOUND); refute_submodule_exists(g_repo, "not-submodule", GIT_EEXISTS); refute_submodule_exists(g_repo, "not", GIT_EEXISTS); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_index", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_INDEX_MODIFIED) != 0); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_head", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_file", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_WD_MODIFIED) != 0); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_untracked_file", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_missing_commits", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); cl_git_pass(git_submodule_status(&status, g_repo,"sm_added_and_uncommited", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_ADDED) != 0); /* removed sm_unchanged for deleted workdir */ cl_git_pass(git_submodule_status(&status, g_repo,"sm_unchanged", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_DELETED) != 0); /* now mkdir sm_unchanged to test uninitialized */ cl_git_pass(git_futils_mkdir_relative("sm_unchanged", "submod2", 0755, 0, NULL)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_unchanged", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_UNINITIALIZED) != 0); /* update sm_changed_head in index */ add_submodule_to_index("sm_changed_head"); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_head", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_MODIFIED) != 0); } void test_submodule_status__ignore_dirty(void) { unsigned int status; git_submodule_ignore_t ign = GIT_SUBMODULE_IGNORE_DIRTY; rm_submodule("sm_unchanged"); refute_submodule_exists(g_repo, "just_a_dir", GIT_ENOTFOUND); refute_submodule_exists(g_repo, "not-submodule", GIT_EEXISTS); refute_submodule_exists(g_repo, "not", GIT_EEXISTS); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_index", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_head", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_file", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_untracked_file", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_missing_commits", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); cl_git_pass(git_submodule_status(&status, g_repo,"sm_added_and_uncommited", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_ADDED) != 0); /* removed sm_unchanged for deleted workdir */ cl_git_pass(git_submodule_status(&status, g_repo,"sm_unchanged", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_DELETED) != 0); /* now mkdir sm_unchanged to test uninitialized */ cl_git_pass(git_futils_mkdir_relative("sm_unchanged", "submod2", 0755, 0, NULL)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_unchanged", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_UNINITIALIZED) != 0); /* update sm_changed_head in index */ add_submodule_to_index("sm_changed_head"); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_head", ign)); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_MODIFIED) != 0); } void test_submodule_status__ignore_all(void) { unsigned int status; git_submodule_ignore_t ign = GIT_SUBMODULE_IGNORE_ALL; rm_submodule("sm_unchanged"); refute_submodule_exists(g_repo, "just_a_dir", GIT_ENOTFOUND); refute_submodule_exists(g_repo, "not-submodule", GIT_EEXISTS); refute_submodule_exists(g_repo, "not", GIT_EEXISTS); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_index", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_head", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_file", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_untracked_file", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_missing_commits", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_added_and_uncommited", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); /* removed sm_unchanged for deleted workdir */ cl_git_pass(git_submodule_status(&status, g_repo,"sm_unchanged", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); /* now mkdir sm_unchanged to test uninitialized */ cl_git_pass(git_futils_mkdir_relative("sm_unchanged", "submod2", 0755, 0, NULL)); cl_git_pass(git_submodule_status(&status, g_repo,"sm_unchanged", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); /* update sm_changed_head in index */ add_submodule_to_index("sm_changed_head"); cl_git_pass(git_submodule_status(&status, g_repo,"sm_changed_head", ign)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); } typedef struct { size_t counter; const char **paths; int *statuses; } submodule_expectations; static int confirm_submodule_status( const char *path, unsigned int status_flags, void *payload) { submodule_expectations *exp = payload; while (exp->statuses[exp->counter] < 0) exp->counter++; cl_assert_equal_i(exp->statuses[exp->counter], (int)status_flags); cl_assert_equal_s(exp->paths[exp->counter++], path); GIT_UNUSED(status_flags); return 0; } void test_submodule_status__iterator(void) { git_iterator *iter; git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT; const git_index_entry *entry; size_t i; static const char *expected[] = { ".gitmodules", "just_a_dir/", "just_a_dir/contents", "just_a_file", "not-submodule/", "not-submodule/README.txt", "not/", "not/README.txt", "README.txt", "sm_added_and_uncommited", "sm_changed_file", "sm_changed_head", "sm_changed_index", "sm_changed_untracked_file", "sm_missing_commits", "sm_unchanged", NULL }; static int expected_flags[] = { GIT_STATUS_INDEX_MODIFIED | GIT_STATUS_WT_MODIFIED, /* ".gitmodules" */ -1, /* "just_a_dir/" will be skipped */ GIT_STATUS_CURRENT, /* "just_a_dir/contents" */ GIT_STATUS_CURRENT, /* "just_a_file" */ GIT_STATUS_WT_NEW, /* "not-submodule/" untracked item */ -1, /* "not-submodule/README.txt" */ GIT_STATUS_WT_NEW, /* "not/" untracked item */ -1, /* "not/README.txt" */ GIT_STATUS_CURRENT, /* "README.txt */ GIT_STATUS_INDEX_NEW, /* "sm_added_and_uncommited" */ GIT_STATUS_WT_MODIFIED, /* "sm_changed_file" */ GIT_STATUS_WT_MODIFIED, /* "sm_changed_head" */ GIT_STATUS_WT_MODIFIED, /* "sm_changed_index" */ GIT_STATUS_WT_MODIFIED, /* "sm_changed_untracked_file" */ GIT_STATUS_WT_MODIFIED, /* "sm_missing_commits" */ GIT_STATUS_CURRENT, /* "sm_unchanged" */ 0 }; submodule_expectations exp = { 0, expected, expected_flags }; git_status_options opts = GIT_STATUS_OPTIONS_INIT; git_index *index; iter_opts.flags = GIT_ITERATOR_IGNORE_CASE | GIT_ITERATOR_INCLUDE_TREES; cl_git_pass(git_repository_index(&index, g_repo)); cl_git_pass(git_iterator_for_workdir(&iter, g_repo, index, NULL, &iter_opts)); for (i = 0; !git_iterator_advance(&entry, iter); ++i) cl_assert_equal_s(expected[i], entry->path); git_iterator_free(iter); git_index_free(index); opts.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_INCLUDE_UNMODIFIED | GIT_STATUS_OPT_INCLUDE_IGNORED | GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS | GIT_STATUS_OPT_SORT_CASE_INSENSITIVELY; cl_git_pass(git_status_foreach_ext( g_repo, &opts, confirm_submodule_status, &exp)); } void test_submodule_status__untracked_dirs_containing_ignored_files(void) { unsigned int status, expected; cl_git_append2file( "submod2/.git/modules/sm_unchanged/info/exclude", "\n*.ignored\n"); cl_git_pass( git_futils_mkdir_relative("sm_unchanged/directory", "submod2", 0755, 0, NULL)); cl_git_mkfile( "submod2/sm_unchanged/directory/i_am.ignored", "ignore this file, please\n"); status = get_submodule_status(g_repo, "sm_unchanged"); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); expected = GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_IN_WD; cl_assert(status == expected); }
libgit2-main
tests/libgit2/submodule/status.c
#include "clar_libgit2.h" #include "posix.h" #include "path.h" #include "submodule_helpers.h" #include "config/config_helpers.h" #include "futils.h" #include "repository.h" #include "git2/sys/commit.h" static git_repository *g_repo = NULL; static const char *valid_blob_id = "fa49b077972391ad58037050f2a75f74e3671e92"; void test_submodule_add__cleanup(void) { cl_git_sandbox_cleanup(); } static void assert_submodule_url(const char* name, const char *url) { git_str key = GIT_STR_INIT; cl_git_pass(git_str_printf(&key, "submodule.%s.url", name)); assert_config_entry_value(g_repo, git_str_cstr(&key), url); git_str_dispose(&key); } void test_submodule_add__url_absolute(void) { git_submodule *sm; git_repository *repo; git_str dot_git_content = GIT_STR_INIT; g_repo = setup_fixture_submod2(); /* re-add existing submodule */ cl_git_fail_with( GIT_EEXISTS, git_submodule_add_setup(NULL, g_repo, "whatever", "sm_unchanged", 1)); /* add a submodule using a gitlink */ cl_git_pass( git_submodule_add_setup(&sm, g_repo, "https://github.com/libgit2/libgit2.git", "sm_libgit2", 1) ); git_submodule_free(sm); cl_assert(git_fs_path_isfile("submod2/" "sm_libgit2" "/.git")); cl_assert(git_fs_path_isdir("submod2/.git/modules")); cl_assert(git_fs_path_isdir("submod2/.git/modules/" "sm_libgit2")); cl_assert(git_fs_path_isfile("submod2/.git/modules/" "sm_libgit2" "/HEAD")); assert_submodule_url("sm_libgit2", "https://github.com/libgit2/libgit2.git"); cl_git_pass(git_repository_open(&repo, "submod2/" "sm_libgit2")); /* Verify worktree path is relative */ assert_config_entry_value(repo, "core.worktree", "../../../sm_libgit2/"); /* Verify gitdir path is relative */ cl_git_pass(git_futils_readbuffer(&dot_git_content, "submod2/" "sm_libgit2" "/.git")); cl_assert_equal_s("gitdir: ../.git/modules/sm_libgit2/", dot_git_content.ptr); git_repository_free(repo); git_str_dispose(&dot_git_content); /* add a submodule not using a gitlink */ cl_git_pass( git_submodule_add_setup(&sm, g_repo, "https://github.com/libgit2/libgit2.git", "sm_libgit2b", 0) ); git_submodule_free(sm); cl_assert(git_fs_path_isdir("submod2/" "sm_libgit2b" "/.git")); cl_assert(git_fs_path_isfile("submod2/" "sm_libgit2b" "/.git/HEAD")); cl_assert(!git_fs_path_exists("submod2/.git/modules/" "sm_libgit2b")); assert_submodule_url("sm_libgit2b", "https://github.com/libgit2/libgit2.git"); } void test_submodule_add__url_relative(void) { git_submodule *sm; git_remote *remote; git_strarray problems = {0}; /* default remote url is https://github.com/libgit2/false.git */ g_repo = cl_git_sandbox_init("testrepo2"); /* make sure we don't default to origin - rename origin -> test_remote */ cl_git_pass(git_remote_rename(&problems, g_repo, "origin", "test_remote")); cl_assert_equal_i(0, problems.count); git_strarray_dispose(&problems); cl_git_fail(git_remote_lookup(&remote, g_repo, "origin")); cl_git_pass( git_submodule_add_setup(&sm, g_repo, "../TestGitRepository", "TestGitRepository", 1) ); git_submodule_free(sm); assert_submodule_url("TestGitRepository", "https://github.com/libgit2/TestGitRepository"); } void test_submodule_add__url_relative_to_origin(void) { git_submodule *sm; /* default remote url is https://github.com/libgit2/false.git */ g_repo = cl_git_sandbox_init("testrepo2"); cl_git_pass( git_submodule_add_setup(&sm, g_repo, "../TestGitRepository", "TestGitRepository", 1) ); git_submodule_free(sm); assert_submodule_url("TestGitRepository", "https://github.com/libgit2/TestGitRepository"); } void test_submodule_add__url_relative_to_workdir(void) { git_submodule *sm; /* In this repo, HEAD (master) has no remote tracking branc h*/ g_repo = cl_git_sandbox_init("testrepo"); cl_git_pass( git_submodule_add_setup(&sm, g_repo, "./", "TestGitRepository", 1) ); git_submodule_free(sm); assert_submodule_url("TestGitRepository", git_repository_workdir(g_repo)); } static void test_add_entry( git_index *index, const char *idstr, const char *path, git_filemode_t mode) { git_index_entry entry = {{0}}; cl_git_pass(git_oid__fromstr(&entry.id, idstr, GIT_OID_SHA1)); entry.path = path; entry.mode = mode; cl_git_pass(git_index_add(index, &entry)); } void test_submodule_add__path_exists_in_index(void) { git_index *index; git_submodule *sm; git_str filename = GIT_STR_INIT; g_repo = cl_git_sandbox_init("testrepo"); cl_git_pass(git_str_joinpath(&filename, "subdirectory", "test.txt")); cl_git_pass(git_repository_index__weakptr(&index, g_repo)); test_add_entry(index, valid_blob_id, filename.ptr, GIT_FILEMODE_BLOB); cl_git_fail_with(git_submodule_add_setup(&sm, g_repo, "./", "subdirectory", 1), GIT_EEXISTS); git_submodule_free(sm); git_str_dispose(&filename); } void test_submodule_add__file_exists_in_index(void) { git_index *index; git_submodule *sm; git_str name = GIT_STR_INIT; g_repo = cl_git_sandbox_init("testrepo"); cl_git_pass(git_repository_index__weakptr(&index, g_repo)); test_add_entry(index, valid_blob_id, "subdirectory", GIT_FILEMODE_BLOB); cl_git_fail_with(git_submodule_add_setup(&sm, g_repo, "./", "subdirectory", 1), GIT_EEXISTS); git_submodule_free(sm); git_str_dispose(&name); } void test_submodule_add__submodule_clone(void) { git_oid tree_id, commit_id; git_signature *sig; git_submodule *sm; git_index *index; g_repo = cl_git_sandbox_init("empty_standard_repo"); /* Create the submodule structure, clone into it and finalize */ cl_git_pass(git_submodule_add_setup(&sm, g_repo, cl_fixture("testrepo.git"), "testrepo-add", true)); cl_git_pass(git_submodule_clone(NULL, sm, NULL)); cl_git_pass(git_submodule_add_finalize(sm)); /* Create the submodule commit */ cl_git_pass(git_repository_index(&index, g_repo)); cl_git_pass(git_index_write_tree(&tree_id, index)); cl_git_pass(git_signature_now(&sig, "Submoduler", "submoduler@local")); cl_git_pass(git_commit_create_from_ids(&commit_id, g_repo, "HEAD", sig, sig, NULL, "A submodule\n", &tree_id, 0, NULL)); assert_submodule_exists(g_repo, "testrepo-add"); git_signature_free(sig); git_submodule_free(sm); git_index_free(index); } void test_submodule_add__submodule_clone_into_nonempty_dir_succeeds(void) { git_submodule *sm; g_repo = cl_git_sandbox_init("empty_standard_repo"); cl_git_pass(p_mkdir("empty_standard_repo/sm", 0777)); cl_git_mkfile("empty_standard_repo/sm/foobar", ""); /* Create the submodule structure, clone into it and finalize */ cl_git_pass(git_submodule_add_setup(&sm, g_repo, cl_fixture("testrepo.git"), "sm", true)); cl_git_pass(git_submodule_clone(NULL, sm, NULL)); cl_git_pass(git_submodule_add_finalize(sm)); cl_assert(git_fs_path_exists("empty_standard_repo/sm/foobar")); assert_submodule_exists(g_repo, "sm"); git_submodule_free(sm); } void test_submodule_add__submodule_clone_twice_fails(void) { git_submodule *sm; g_repo = cl_git_sandbox_init("empty_standard_repo"); /* Create the submodule structure, clone into it and finalize */ cl_git_pass(git_submodule_add_setup(&sm, g_repo, cl_fixture("testrepo.git"), "sm", true)); cl_git_pass(git_submodule_clone(NULL, sm, NULL)); cl_git_pass(git_submodule_add_finalize(sm)); cl_git_fail(git_submodule_clone(NULL, sm, NULL)); git_submodule_free(sm); }
libgit2-main
tests/libgit2/submodule/add.c
#include "clar_libgit2.h" #include "posix.h" #include "path.h" #include "submodule_helpers.h" #include "config/config_helpers.h" static git_repository *g_repo = NULL; #define SM_LIBGIT2_URL "https://github.com/libgit2/libgit2.git" #define SM_LIBGIT2_BRANCH "github-branch" #define SM_LIBGIT2 "sm_libgit2" void test_submodule_modify__initialize(void) { g_repo = setup_fixture_submod2(); } static int delete_one_config(const git_config_entry *entry, void *payload) { git_config *cfg = payload; return git_config_delete_entry(cfg, entry->name); } static int init_one_submodule( git_submodule *sm, const char *name, void *payload) { GIT_UNUSED(name); GIT_UNUSED(payload); return git_submodule_init(sm, false); } void test_submodule_modify__init(void) { git_config *cfg; const char *str; /* erase submodule data from .git/config */ cl_git_pass(git_repository_config(&cfg, g_repo)); cl_git_pass( git_config_foreach_match(cfg, "submodule\\..*", delete_one_config, cfg)); git_config_free(cfg); /* confirm no submodule data in config */ cl_git_pass(git_repository_config_snapshot(&cfg, g_repo)); cl_git_fail_with(GIT_ENOTFOUND, git_config_get_string(&str, cfg, "submodule.sm_unchanged.url")); cl_git_fail_with(GIT_ENOTFOUND, git_config_get_string(&str, cfg, "submodule.sm_changed_head.url")); cl_git_fail_with(GIT_ENOTFOUND, git_config_get_string(&str, cfg, "submodule.sm_added_and_uncommited.url")); git_config_free(cfg); /* call init and see that settings are copied */ cl_git_pass(git_submodule_foreach(g_repo, init_one_submodule, NULL)); /* confirm submodule data in config */ cl_git_pass(git_repository_config_snapshot(&cfg, g_repo)); cl_git_pass(git_config_get_string(&str, cfg, "submodule.sm_unchanged.url")); cl_assert(git__suffixcmp(str, "/submod2_target") == 0); cl_git_pass(git_config_get_string(&str, cfg, "submodule.sm_changed_head.url")); cl_assert(git__suffixcmp(str, "/submod2_target") == 0); cl_git_pass(git_config_get_string(&str, cfg, "submodule.sm_added_and_uncommited.url")); cl_assert(git__suffixcmp(str, "/submod2_target") == 0); git_config_free(cfg); } static int sync_one_submodule( git_submodule *sm, const char *name, void *payload) { GIT_UNUSED(name); GIT_UNUSED(payload); return git_submodule_sync(sm); } static void assert_submodule_url_is_synced( git_submodule *sm, const char *parent_key, const char *child_key) { git_repository *smrepo; assert_config_entry_value(g_repo, parent_key, git_submodule_url(sm)); cl_git_pass(git_submodule_open(&smrepo, sm)); assert_config_entry_value(smrepo, child_key, git_submodule_url(sm)); git_repository_free(smrepo); } void test_submodule_modify__sync(void) { git_submodule *sm1, *sm2, *sm3; git_config *cfg; const char *str; #define SM1 "sm_unchanged" #define SM2 "sm_changed_head" #define SM3 "sm_added_and_uncommited" /* look up some submodules */ cl_git_pass(git_submodule_lookup(&sm1, g_repo, SM1)); cl_git_pass(git_submodule_lookup(&sm2, g_repo, SM2)); cl_git_pass(git_submodule_lookup(&sm3, g_repo, SM3)); /* At this point, the .git/config URLs for the submodules have * not be rewritten with the absolute paths (although the * .gitmodules have. Let's confirm that they DO NOT match * yet, then we can do a sync to make them match... */ /* check submodule info does not match before sync */ cl_git_pass(git_repository_config_snapshot(&cfg, g_repo)); cl_git_pass(git_config_get_string(&str, cfg, "submodule."SM1".url")); cl_assert(strcmp(git_submodule_url(sm1), str) != 0); cl_git_pass(git_config_get_string(&str, cfg, "submodule."SM2".url")); cl_assert(strcmp(git_submodule_url(sm2), str) != 0); cl_git_pass(git_config_get_string(&str, cfg, "submodule."SM3".url")); cl_assert(strcmp(git_submodule_url(sm3), str) != 0); git_config_free(cfg); /* sync all the submodules */ cl_git_pass(git_submodule_foreach(g_repo, sync_one_submodule, NULL)); /* check that submodule config is updated */ assert_submodule_url_is_synced( sm1, "submodule."SM1".url", "remote.origin.url"); assert_submodule_url_is_synced( sm2, "submodule."SM2".url", "remote.origin.url"); assert_submodule_url_is_synced( sm3, "submodule."SM3".url", "remote.origin.url"); git_submodule_free(sm1); git_submodule_free(sm2); git_submodule_free(sm3); } static void assert_ignore_change(git_submodule_ignore_t ignore) { git_submodule *sm; cl_git_pass(git_submodule_set_ignore(g_repo, "sm_changed_head", ignore)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_assert_equal_i(ignore, git_submodule_ignore(sm)); git_submodule_free(sm); } void test_submodule_modify__set_ignore(void) { assert_ignore_change(GIT_SUBMODULE_IGNORE_UNTRACKED); assert_ignore_change(GIT_SUBMODULE_IGNORE_NONE); assert_ignore_change(GIT_SUBMODULE_IGNORE_ALL); } static void assert_update_change(git_submodule_update_t update) { git_submodule *sm; cl_git_pass(git_submodule_set_update(g_repo, "sm_changed_head", update)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_assert_equal_i(update, git_submodule_update_strategy(sm)); git_submodule_free(sm); } void test_submodule_modify__set_update(void) { assert_update_change(GIT_SUBMODULE_UPDATE_REBASE); assert_update_change(GIT_SUBMODULE_UPDATE_NONE); assert_update_change(GIT_SUBMODULE_UPDATE_CHECKOUT); } static void assert_recurse_change(git_submodule_recurse_t recurse) { git_submodule *sm; cl_git_pass(git_submodule_set_fetch_recurse_submodules(g_repo, "sm_changed_head", recurse)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_assert_equal_i(recurse, git_submodule_fetch_recurse_submodules(sm)); git_submodule_free(sm); } void test_submodule_modify__set_fetch_recurse_submodules(void) { assert_recurse_change(GIT_SUBMODULE_RECURSE_YES); assert_recurse_change(GIT_SUBMODULE_RECURSE_NO); assert_recurse_change(GIT_SUBMODULE_RECURSE_ONDEMAND); } void test_submodule_modify__set_branch(void) { git_submodule *sm; cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_assert(git_submodule_branch(sm) == NULL); git_submodule_free(sm); cl_git_pass(git_submodule_set_branch(g_repo, "sm_changed_head", SM_LIBGIT2_BRANCH)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_assert_equal_s(SM_LIBGIT2_BRANCH, git_submodule_branch(sm)); git_submodule_free(sm); cl_git_pass(git_submodule_set_branch(g_repo, "sm_changed_head", NULL)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_assert(git_submodule_branch(sm) == NULL); git_submodule_free(sm); } void test_submodule_modify__set_url(void) { git_submodule *sm; cl_git_pass(git_submodule_set_url(g_repo, "sm_changed_head", SM_LIBGIT2_URL)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_assert_equal_s(SM_LIBGIT2_URL, git_submodule_url(sm)); git_submodule_free(sm); } void test_submodule_modify__set_relative_url(void) { git_str path = GIT_STR_INIT; git_repository *repo; git_submodule *sm; cl_git_pass(git_submodule_set_url(g_repo, SM1, "../relative-url")); cl_git_pass(git_submodule_lookup(&sm, g_repo, SM1)); cl_git_pass(git_submodule_sync(sm)); cl_git_pass(git_submodule_open(&repo, sm)); cl_git_pass(git_str_joinpath(&path, clar_sandbox_path(), "relative-url")); assert_config_entry_value(g_repo, "submodule."SM1".url", path.ptr); assert_config_entry_value(repo, "remote.origin.url", path.ptr); git_repository_free(repo); git_submodule_free(sm); git_str_dispose(&path); }
libgit2-main
tests/libgit2/submodule/modify.c
#include "clar_libgit2.h" #include "submodule_helpers.h" #include "path.h" static git_repository *g_parent; static git_repository *g_child; static git_submodule *g_module; void test_submodule_open__initialize(void) { g_parent = setup_fixture_submod2(); } void test_submodule_open__cleanup(void) { git_submodule_free(g_module); git_repository_free(g_child); cl_git_sandbox_cleanup(); g_parent = NULL; g_child = NULL; g_module = NULL; } static void assert_sm_valid(git_repository *parent, git_repository *child, const char *sm_name) { git_str expected = GIT_STR_INIT, actual = GIT_STR_INIT; /* assert working directory */ cl_git_pass(git_str_joinpath(&expected, git_repository_workdir(parent), sm_name)); cl_git_pass(git_fs_path_prettify_dir(&expected, expected.ptr, NULL)); cl_git_pass(git_str_sets(&actual, git_repository_workdir(child))); cl_git_pass(git_fs_path_prettify_dir(&actual, actual.ptr, NULL)); cl_assert_equal_s(expected.ptr, actual.ptr); git_str_clear(&expected); git_str_clear(&actual); /* assert common directory */ cl_git_pass(git_str_joinpath(&expected, git_repository_commondir(parent), "modules")); cl_git_pass(git_str_joinpath(&expected, expected.ptr, sm_name)); cl_git_pass(git_fs_path_prettify_dir(&expected, expected.ptr, NULL)); cl_git_pass(git_str_sets(&actual, git_repository_commondir(child))); cl_git_pass(git_fs_path_prettify_dir(&actual, actual.ptr, NULL)); cl_assert_equal_s(expected.ptr, actual.ptr); /* assert git directory */ cl_git_pass(git_str_sets(&actual, git_repository_path(child))); cl_git_pass(git_fs_path_prettify_dir(&actual, actual.ptr, NULL)); cl_assert_equal_s(expected.ptr, actual.ptr); git_str_dispose(&expected); git_str_dispose(&actual); } void test_submodule_open__opening_via_lookup_succeeds(void) { cl_git_pass(git_submodule_lookup(&g_module, g_parent, "sm_unchanged")); cl_git_pass(git_submodule_open(&g_child, g_module)); assert_sm_valid(g_parent, g_child, "sm_unchanged"); } void test_submodule_open__direct_open_succeeds(void) { git_str path = GIT_STR_INIT; cl_git_pass(git_str_joinpath(&path, git_repository_workdir(g_parent), "sm_unchanged")); cl_git_pass(git_repository_open(&g_child, path.ptr)); assert_sm_valid(g_parent, g_child, "sm_unchanged"); git_str_dispose(&path); } void test_submodule_open__direct_open_succeeds_for_broken_sm_with_gitdir(void) { git_str path = GIT_STR_INIT; /* * This is actually not a valid submodule, but we * encountered at least one occasion where the gitdir * file existed inside of a submodule's gitdir. As we are * now able to open these submodules correctly, we still * add a test for this. */ cl_git_mkfile("submod2/.git/modules/sm_unchanged/gitdir", ".git"); cl_git_pass(git_str_joinpath(&path, git_repository_workdir(g_parent), "sm_unchanged")); cl_git_pass(git_repository_open(&g_child, path.ptr)); assert_sm_valid(g_parent, g_child, "sm_unchanged"); git_str_dispose(&path); }
libgit2-main
tests/libgit2/submodule/open.c
#include "clar_libgit2.h" #include "clar_libgit2_trace.h" #include "trace.h" static int written = 0; static void trace_callback(git_trace_level_t level, const char *message) { GIT_UNUSED(level); cl_assert(strcmp(message, "Hello world!") == 0); written = 1; } void test_trace_trace__initialize(void) { /* If global tracing is enabled, disable for the duration of this test. */ cl_global_trace_disable(); git_trace_set(GIT_TRACE_INFO, trace_callback); written = 0; } void test_trace_trace__cleanup(void) { git_trace_set(GIT_TRACE_NONE, NULL); /* If global tracing was enabled, restart it. */ cl_global_trace_register(); } void test_trace_trace__sets(void) { #ifdef GIT_TRACE cl_assert(git_trace_level() == GIT_TRACE_INFO); #else cl_skip(); #endif } void test_trace_trace__can_reset(void) { #ifdef GIT_TRACE cl_assert(git_trace_level() == GIT_TRACE_INFO); cl_git_pass(git_trace_set(GIT_TRACE_ERROR, trace_callback)); cl_assert(written == 0); git_trace(GIT_TRACE_INFO, "Hello %s!", "world"); cl_assert(written == 0); git_trace(GIT_TRACE_ERROR, "Hello %s!", "world"); cl_assert(written == 1); #else cl_skip(); #endif } void test_trace_trace__can_unset(void) { #ifdef GIT_TRACE cl_assert(git_trace_level() == GIT_TRACE_INFO); cl_git_pass(git_trace_set(GIT_TRACE_NONE, NULL)); cl_assert(git_trace_level() == GIT_TRACE_NONE); cl_assert(written == 0); git_trace(GIT_TRACE_FATAL, "Hello %s!", "world"); cl_assert(written == 0); #else cl_skip(); #endif } void test_trace_trace__skips_higher_level(void) { #ifdef GIT_TRACE cl_assert(written == 0); git_trace(GIT_TRACE_DEBUG, "Hello %s!", "world"); cl_assert(written == 0); #else cl_skip(); #endif } void test_trace_trace__writes(void) { #ifdef GIT_TRACE cl_assert(written == 0); git_trace(GIT_TRACE_INFO, "Hello %s!", "world"); cl_assert(written == 1); #else cl_skip(); #endif } void test_trace_trace__writes_lower_level(void) { #ifdef GIT_TRACE cl_assert(written == 0); git_trace(GIT_TRACE_ERROR, "Hello %s!", "world"); cl_assert(written == 1); #else cl_skip(); #endif }
libgit2-main
tests/libgit2/trace/trace.c
#include "clar_libgit2.h" #include "win32/w32_leakcheck.h" #if defined(GIT_WIN32_LEAKCHECK) static void a(void) { char buf[10000]; cl_assert(git_win32_leakcheck_stack(buf, sizeof(buf), 0, NULL, NULL) == 0); #if 0 fprintf(stderr, "Stacktrace from [%s:%d]:\n%s\n", __FILE__, __LINE__, buf); #endif } static void b(void) { a(); } static void c(void) { b(); } #endif void test_trace_windows_stacktrace__basic(void) { #if defined(GIT_WIN32_LEAKCHECK) c(); #endif } void test_trace_windows_stacktrace__leaks(void) { #if defined(GIT_WIN32_LEAKCHECK) void * p1; void * p2; void * p3; void * p4; int before, after; int leaks; int error; /* remember outstanding leaks due to set setup * and set mark/checkpoint. */ before = git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET | GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_TOTAL | GIT_WIN32_LEAKCHECK_STACKTRACE_SET_MARK, NULL); p1 = git__malloc(5); leaks = git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET | GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_SINCE_MARK, "p1"); cl_assert_equal_i(1, leaks); p2 = git__malloc(5); leaks = git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET | GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_SINCE_MARK, "p1,p2"); cl_assert_equal_i(2, leaks); p3 = git__malloc(5); leaks = git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET | GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_SINCE_MARK, "p1,p2,p3"); cl_assert_equal_i(3, leaks); git__free(p2); leaks = git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET | GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_SINCE_MARK, "p1,p3"); cl_assert_equal_i(2, leaks); /* move the mark. only new leaks should appear afterwards */ error = git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_SET_MARK, NULL); /* cannot use cl_git_pass() since that may allocate memory. */ cl_assert_equal_i(0, error); leaks = git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET | GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_SINCE_MARK, "not_p1,not_p3"); cl_assert_equal_i(0, leaks); p4 = git__malloc(5); leaks = git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET | GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_SINCE_MARK, "p4,not_p1,not_p3"); cl_assert_equal_i(1, leaks); git__free(p1); git__free(p3); leaks = git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET | GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_SINCE_MARK, "p4"); cl_assert_equal_i(1, leaks); git__free(p4); leaks = git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET | GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_SINCE_MARK, "end"); cl_assert_equal_i(0, leaks); /* confirm current absolute leaks count matches beginning value. */ after = git_win32_leakcheck_stacktrace_dump( GIT_WIN32_LEAKCHECK_STACKTRACE_QUIET | GIT_WIN32_LEAKCHECK_STACKTRACE_LEAKS_TOTAL, "total"); cl_assert_equal_i(before, after); #endif } #if defined(GIT_WIN32_LEAKCHECK) static void aux_cb_alloc__1(unsigned int *aux_id) { static unsigned int aux_counter = 0; *aux_id = aux_counter++; } static void aux_cb_lookup__1(unsigned int aux_id, char *aux_msg, size_t aux_msg_len) { p_snprintf(aux_msg, aux_msg_len, "\tQQ%08x\n", aux_id); } #endif void test_trace_windows_stacktrace__aux1(void) { #if defined(GIT_WIN32_LEAKCHECK) git_win32_leakcheck_stack_set_aux_cb(aux_cb_alloc__1, aux_cb_lookup__1); c(); c(); c(); c(); git_win32_leakcheck_stack_set_aux_cb(NULL, NULL); #endif }
libgit2-main
tests/libgit2/trace/windows/stacktrace.c
#include "clar_libgit2.h" #include "git2/sys/remote.h" #include "git2/sys/transport.h" static const char *proxy_url = "https://proxy"; static git_transport _transport = GIT_TRANSPORT_INIT; static int dummy_transport(git_transport **transport, git_remote *owner, void *param) { *transport = &_transport; GIT_UNUSED(owner); GIT_UNUSED(param); return 0; } void test_transport_register__custom_transport(void) { git_transport *transport; cl_git_pass(git_transport_register("something", dummy_transport, NULL)); cl_git_pass(git_transport_new(&transport, NULL, "something://somepath")); cl_assert(transport == &_transport); cl_git_pass(git_transport_unregister("something")); } void test_transport_register__custom_transport_error_doubleregister(void) { cl_git_pass(git_transport_register("something", dummy_transport, NULL)); cl_git_fail_with(git_transport_register("something", dummy_transport, NULL), GIT_EEXISTS); cl_git_pass(git_transport_unregister("something")); } void test_transport_register__custom_transport_error_remove_non_existing(void) { cl_git_fail_with(git_transport_unregister("something"), GIT_ENOTFOUND); } void test_transport_register__custom_transport_ssh(void) { const char *urls[] = { "ssh://somehost:somepath", "ssh+git://somehost:somepath", "git+ssh://somehost:somepath", "git@somehost:somepath", "ssh://somehost:somepath%20with%20%spaces", "ssh://somehost:somepath with spaces" }; git_transport *transport; unsigned i; for (i = 0; i < ARRAY_SIZE(urls); i++) { #ifndef GIT_SSH cl_git_fail_with(git_transport_new(&transport, NULL, urls[i]), -1); #else cl_git_pass(git_transport_new(&transport, NULL, urls[i])); transport->free(transport); #endif } cl_git_pass(git_transport_register("ssh", dummy_transport, NULL)); cl_git_pass(git_transport_new(&transport, NULL, "git@somehost:somepath")); cl_assert(transport == &_transport); cl_git_pass(git_transport_unregister("ssh")); for (i = 0; i < ARRAY_SIZE(urls); i++) { #ifndef GIT_SSH cl_git_fail_with(git_transport_new(&transport, NULL, urls[i]), -1); #else cl_git_pass(git_transport_new(&transport, NULL, urls[i])); transport->free(transport); #endif } } static int custom_subtransport_stream__read( git_smart_subtransport_stream *stream, char *buffer, size_t buf_size, size_t *bytes_read) { GIT_UNUSED(stream); GIT_UNUSED(buffer); GIT_UNUSED(buf_size); *bytes_read = 0; git_error_set_str(42, "unimplemented"); return GIT_EUSER; } static int custom_subtransport_stream__write( git_smart_subtransport_stream *stream, const char *buffer, size_t len) { GIT_UNUSED(stream); GIT_UNUSED(buffer); GIT_UNUSED(len); git_error_set_str(42, "unimplemented"); return GIT_EUSER; } static void custom_subtransport_stream__free( git_smart_subtransport_stream *stream) { git__free(stream); } struct custom_subtransport { git_smart_subtransport subtransport; git_transport *owner; int *called; }; static int custom_subtransport__action( git_smart_subtransport_stream **out, git_smart_subtransport *transport, const char *url, git_smart_service_t action) { struct custom_subtransport *t = (struct custom_subtransport *)transport; git_remote_connect_options opts = GIT_REMOTE_CONNECT_OPTIONS_INIT; int ret; GIT_UNUSED(url); GIT_UNUSED(action); ret = git_transport_remote_connect_options(&opts, t->owner); /* increase the counter once if this function was called at all and once more if the URL matches. */ (*t->called)++; if (strcmp(proxy_url, opts.proxy_opts.url) == 0) (*t->called)++; git_remote_connect_options_dispose(&opts); *out = git__calloc(1, sizeof(git_smart_subtransport_stream)); (*out)->subtransport = transport; (*out)->read = custom_subtransport_stream__read; (*out)->write = custom_subtransport_stream__write; (*out)->free = custom_subtransport_stream__free; return ret; } static int custom_subtransport__close(git_smart_subtransport *transport) { GIT_UNUSED(transport); return 0; } static void custom_subtransport__free(git_smart_subtransport *transport) { GIT_UNUSED(transport); git__free(transport); } static int custom_transport_callback(git_smart_subtransport **out, git_transport *owner, void *param) { struct custom_subtransport *subtransport = git__calloc(1, sizeof(struct custom_subtransport)); subtransport->called = (int *)param; subtransport->owner = owner; subtransport->subtransport.action = custom_subtransport__action; subtransport->subtransport.close = custom_subtransport__close; subtransport->subtransport.free = custom_subtransport__free; *out = &subtransport->subtransport; return 0; } static int custom_transport(git_transport **out, git_remote *owner, void *param) { struct git_smart_subtransport_definition definition; definition.callback = custom_transport_callback; definition.rpc = false; definition.param = param; return git_transport_smart(out, owner, &definition); } void test_transport_register__custom_transport_callbacks(void) { git_transport *transport; int called = 0; const char *url = "custom://somepath"; git_remote_connect_options opts = GIT_REMOTE_CONNECT_OPTIONS_INIT; git_repository *repo; git_remote *remote; cl_git_pass(git_repository_init(&repo, "./transport", 0)); cl_git_pass(git_remote_create(&remote, repo, "test", cl_fixture("testrepo.git"))); cl_git_pass(git_transport_register("custom", custom_transport, &called)); cl_git_pass(git_transport_new(&transport, remote, url)); opts.follow_redirects = GIT_REMOTE_REDIRECT_NONE; opts.proxy_opts.url = proxy_url; /* This is expected to fail, since the subtransport_stream is not implemented */ transport->connect(transport, url, GIT_SERVICE_UPLOADPACK_LS, &opts); /* the counter is increased twice if everything goes as planned */ cl_assert_equal_i(2, called); cl_git_pass(transport->close(transport)); transport->free(transport); cl_git_pass(git_transport_unregister("custom")); git_remote_free(remote); git_repository_free(repo); cl_fixture_cleanup("testrepo.git"); }
libgit2-main
tests/libgit2/transport/register.c
#include "clar_libgit2.h" #include "settings.h" void test_core_useragent__get(void) { const char *custom_name = "super duper git"; git_str buf = GIT_STR_INIT; cl_assert_equal_p(NULL, git_libgit2__user_agent()); cl_git_pass(git_libgit2_opts(GIT_OPT_SET_USER_AGENT, custom_name)); cl_assert_equal_s(custom_name, git_libgit2__user_agent()); cl_git_pass(git_libgit2_opts(GIT_OPT_GET_USER_AGENT, &buf)); cl_assert_equal_s(custom_name, buf.ptr); git_str_dispose(&buf); }
libgit2-main
tests/libgit2/core/useragent.c
#include "clar_libgit2.h" #include "git2/sys/hashsig.h" #include "futils.h" #define SIMILARITY_TEST_DATA_1 \ "000\n001\n002\n003\n004\n005\n006\n007\n008\n009\n" \ "010\n011\n012\n013\n014\n015\n016\n017\n018\n019\n" \ "020\n021\n022\n023\n024\n025\n026\n027\n028\n029\n" \ "030\n031\n032\n033\n034\n035\n036\n037\n038\n039\n" \ "040\n041\n042\n043\n044\n045\n046\n047\n048\n049\n" void test_core_hashsig__similarity_metric(void) { git_hashsig *a, *b; git_str buf = GIT_STR_INIT; int sim; /* in the first case, we compare data to itself and expect 100% match */ cl_git_pass(git_str_sets(&buf, SIMILARITY_TEST_DATA_1)); cl_git_pass(git_hashsig_create(&a, buf.ptr, buf.size, GIT_HASHSIG_NORMAL)); cl_git_pass(git_hashsig_create(&b, buf.ptr, buf.size, GIT_HASHSIG_NORMAL)); cl_assert_equal_i(100, git_hashsig_compare(a, b)); git_hashsig_free(a); git_hashsig_free(b); /* if we change just a single byte, how much does that change magnify? */ cl_git_pass(git_str_sets(&buf, SIMILARITY_TEST_DATA_1)); cl_git_pass(git_hashsig_create(&a, buf.ptr, buf.size, GIT_HASHSIG_NORMAL)); cl_git_pass(git_str_sets(&buf, "000\n001\n002\n003\n004\n005\n006\n007\n008\n009\n" \ "010\n011\n012\n013\n014\n015\n016\n017\n018\n019\n" \ "x020x\n021\n022\n023\n024\n025\n026\n027\n028\n029\n" \ "030\n031\n032\n033\n034\n035\n036\n037\n038\n039\n" \ "040\n041\n042\n043\n044\n045\n046\n047\n048\n049\n" )); cl_git_pass(git_hashsig_create(&b, buf.ptr, buf.size, GIT_HASHSIG_NORMAL)); sim = git_hashsig_compare(a, b); cl_assert_in_range(95, sim, 100); /* expect >95% similarity */ git_hashsig_free(a); git_hashsig_free(b); /* let's try comparing data to a superset of itself */ cl_git_pass(git_str_sets(&buf, SIMILARITY_TEST_DATA_1)); cl_git_pass(git_hashsig_create(&a, buf.ptr, buf.size, GIT_HASHSIG_NORMAL)); cl_git_pass(git_str_sets(&buf, SIMILARITY_TEST_DATA_1 "050\n051\n052\n053\n054\n055\n056\n057\n058\n059\n")); cl_git_pass(git_hashsig_create(&b, buf.ptr, buf.size, GIT_HASHSIG_NORMAL)); sim = git_hashsig_compare(a, b); /* 20% lines added ~= 10% lines changed */ cl_assert_in_range(85, sim, 95); /* expect similarity around 90% */ git_hashsig_free(a); git_hashsig_free(b); /* what if we keep about half the original data and add half new */ cl_git_pass(git_str_sets(&buf, SIMILARITY_TEST_DATA_1)); cl_git_pass(git_hashsig_create(&a, buf.ptr, buf.size, GIT_HASHSIG_NORMAL)); cl_git_pass(git_str_sets(&buf, "000\n001\n002\n003\n004\n005\n006\n007\n008\n009\n" \ "010\n011\n012\n013\n014\n015\n016\n017\n018\n019\n" \ "020x\n021\n022\n023\n024\n" \ "x25\nx26\nx27\nx28\nx29\n" \ "x30\nx31\nx32\nx33\nx34\nx35\nx36\nx37\nx38\nx39\n" \ "x40\nx41\nx42\nx43\nx44\nx45\nx46\nx47\nx48\nx49\n" )); cl_git_pass(git_hashsig_create(&b, buf.ptr, buf.size, GIT_HASHSIG_NORMAL)); sim = git_hashsig_compare(a, b); /* 50% lines changed */ cl_assert_in_range(40, sim, 60); /* expect in the 40-60% similarity range */ git_hashsig_free(a); git_hashsig_free(b); /* lastly, let's check that we can hash file content as well */ cl_git_pass(git_str_sets(&buf, SIMILARITY_TEST_DATA_1)); cl_git_pass(git_hashsig_create(&a, buf.ptr, buf.size, GIT_HASHSIG_NORMAL)); cl_git_pass(git_futils_mkdir("scratch", 0755, GIT_MKDIR_PATH)); cl_git_mkfile("scratch/testdata", SIMILARITY_TEST_DATA_1); cl_git_pass(git_hashsig_create_fromfile( &b, "scratch/testdata", GIT_HASHSIG_NORMAL)); cl_assert_equal_i(100, git_hashsig_compare(a, b)); git_hashsig_free(a); git_hashsig_free(b); git_str_dispose(&buf); git_futils_rmdir_r("scratch", NULL, GIT_RMDIR_REMOVE_FILES); } void test_core_hashsig__similarity_metric_whitespace(void) { git_hashsig *a, *b; git_str buf = GIT_STR_INIT; int sim, i, j; git_hashsig_option_t opt; const char *tabbed = " for (s = 0; s < sizeof(sep) / sizeof(char); ++s) {\n" " separator = sep[s];\n" " expect = expect_values[s];\n" "\n" " for (j = 0; j < sizeof(b) / sizeof(char*); ++j) {\n" " for (i = 0; i < sizeof(a) / sizeof(char*); ++i) {\n" " git_str_join(&buf, separator, a[i], b[j]);\n" " cl_assert_equal_s(*expect, buf.ptr);\n" " expect++;\n" " }\n" " }\n" " }\n"; const char *spaced = " for (s = 0; s < sizeof(sep) / sizeof(char); ++s) {\n" " separator = sep[s];\n" " expect = expect_values[s];\n" "\n" " for (j = 0; j < sizeof(b) / sizeof(char*); ++j) {\n" " for (i = 0; i < sizeof(a) / sizeof(char*); ++i) {\n" " git_str_join(&buf, separator, a[i], b[j]);\n" " cl_assert_equal_s(*expect, buf.ptr);\n" " expect++;\n" " }\n" " }\n" " }\n"; const char *crlf_spaced2 = " for (s = 0; s < sizeof(sep) / sizeof(char); ++s) {\r\n" " separator = sep[s];\r\n" " expect = expect_values[s];\r\n" "\r\n" " for (j = 0; j < sizeof(b) / sizeof(char*); ++j) {\r\n" " for (i = 0; i < sizeof(a) / sizeof(char*); ++i) {\r\n" " git_str_join(&buf, separator, a[i], b[j]);\r\n" " cl_assert_equal_s(*expect, buf.ptr);\r\n" " expect++;\r\n" " }\r\n" " }\r\n" " }\r\n"; const char *text[3] = { tabbed, spaced, crlf_spaced2 }; /* let's try variations of our own code with whitespace changes */ for (opt = GIT_HASHSIG_NORMAL; opt <= GIT_HASHSIG_SMART_WHITESPACE; ++opt) { for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { cl_git_pass(git_str_sets(&buf, text[i])); cl_git_pass(git_hashsig_create(&a, buf.ptr, buf.size, opt)); cl_git_pass(git_str_sets(&buf, text[j])); cl_git_pass(git_hashsig_create(&b, buf.ptr, buf.size, opt)); sim = git_hashsig_compare(a, b); if (opt == GIT_HASHSIG_NORMAL) { if (i == j) cl_assert_equal_i(100, sim); else cl_assert_in_range(0, sim, 30); /* pretty different */ } else { cl_assert_equal_i(100, sim); } git_hashsig_free(a); git_hashsig_free(b); } } } git_str_dispose(&buf); }
libgit2-main
tests/libgit2/core/hashsig.c
#include "clar_libgit2.h" #include "oidmap.h" static struct { git_oid oid; size_t extra; } test_oids[0x0FFF]; static git_oidmap *g_map; void test_core_oidmap__initialize(void) { uint32_t i, j; for (i = 0; i < ARRAY_SIZE(test_oids); ++i) { uint32_t segment = i / 8; int modi = i - (segment * 8); test_oids[i].extra = i; for (j = 0; j < GIT_OID_SHA1_SIZE / 4; ++j) { test_oids[i].oid.id[j * 4 ] = (unsigned char)modi; test_oids[i].oid.id[j * 4 + 1] = (unsigned char)(modi >> 8); test_oids[i].oid.id[j * 4 + 2] = (unsigned char)(modi >> 16); test_oids[i].oid.id[j * 4 + 3] = (unsigned char)(modi >> 24); } test_oids[i].oid.id[ 8] = (unsigned char)i; test_oids[i].oid.id[ 9] = (unsigned char)(i >> 8); test_oids[i].oid.id[10] = (unsigned char)(i >> 16); test_oids[i].oid.id[11] = (unsigned char)(i >> 24); #ifdef GIT_EXPERIMENTAL_SHA256 test_oids[i].oid.type = GIT_OID_SHA1; #endif } cl_git_pass(git_oidmap_new(&g_map)); } void test_core_oidmap__cleanup(void) { git_oidmap_free(g_map); } void test_core_oidmap__basic(void) { size_t i; for (i = 0; i < ARRAY_SIZE(test_oids); ++i) { cl_assert(!git_oidmap_exists(g_map, &test_oids[i].oid)); cl_git_pass(git_oidmap_set(g_map, &test_oids[i].oid, &test_oids[i])); } for (i = 0; i < ARRAY_SIZE(test_oids); ++i) { cl_assert(git_oidmap_exists(g_map, &test_oids[i].oid)); cl_assert_equal_p(git_oidmap_get(g_map, &test_oids[i].oid), &test_oids[i]); } } void test_core_oidmap__hash_collision(void) { size_t i; for (i = 0; i < ARRAY_SIZE(test_oids); ++i) { cl_assert(!git_oidmap_exists(g_map, &test_oids[i].oid)); cl_git_pass(git_oidmap_set(g_map, &test_oids[i].oid, &test_oids[i])); } for (i = 0; i < ARRAY_SIZE(test_oids); ++i) { cl_assert(git_oidmap_exists(g_map, &test_oids[i].oid)); cl_assert_equal_p(git_oidmap_get(g_map, &test_oids[i].oid), &test_oids[i]); } } void test_core_oidmap__get_succeeds_with_existing_keys(void) { size_t i; for (i = 0; i < ARRAY_SIZE(test_oids); ++i) cl_git_pass(git_oidmap_set(g_map, &test_oids[i].oid, &test_oids[i])); for (i = 0; i < ARRAY_SIZE(test_oids); ++i) cl_assert_equal_p(git_oidmap_get(g_map, &test_oids[i].oid), &test_oids[i]); } void test_core_oidmap__get_fails_with_nonexisting_key(void) { size_t i; /* Do _not_ add last OID to verify that we cannot look it up */ for (i = 0; i < ARRAY_SIZE(test_oids) - 1; ++i) cl_git_pass(git_oidmap_set(g_map, &test_oids[i].oid, &test_oids[i])); cl_assert_equal_p(git_oidmap_get(g_map, &test_oids[ARRAY_SIZE(test_oids) - 1].oid), NULL); } void test_core_oidmap__setting_oid_persists(void) { git_oid oids[] = { GIT_OID_INIT(GIT_OID_SHA1, { 0x01 }), GIT_OID_INIT(GIT_OID_SHA1, { 0x02 }), GIT_OID_INIT(GIT_OID_SHA1, { 0x03 }) }; cl_git_pass(git_oidmap_set(g_map, &oids[0], "one")); cl_git_pass(git_oidmap_set(g_map, &oids[1], "two")); cl_git_pass(git_oidmap_set(g_map, &oids[2], "three")); cl_assert_equal_s(git_oidmap_get(g_map, &oids[0]), "one"); cl_assert_equal_s(git_oidmap_get(g_map, &oids[1]), "two"); cl_assert_equal_s(git_oidmap_get(g_map, &oids[2]), "three"); } void test_core_oidmap__setting_existing_key_updates(void) { git_oid oids[] = { GIT_OID_INIT(GIT_OID_SHA1, { 0x01 }), GIT_OID_INIT(GIT_OID_SHA1, { 0x02 }), GIT_OID_INIT(GIT_OID_SHA1, { 0x03 }) }; cl_git_pass(git_oidmap_set(g_map, &oids[0], "one")); cl_git_pass(git_oidmap_set(g_map, &oids[1], "two")); cl_git_pass(git_oidmap_set(g_map, &oids[2], "three")); cl_assert_equal_i(git_oidmap_size(g_map), 3); cl_git_pass(git_oidmap_set(g_map, &oids[1], "other")); cl_assert_equal_i(git_oidmap_size(g_map), 3); cl_assert_equal_s(git_oidmap_get(g_map, &oids[1]), "other"); }
libgit2-main
tests/libgit2/core/oidmap.c
#include "clar_libgit2.h" #include "futils.h" #include "sysdir.h" #ifdef GIT_WIN32 #define NUM_VARS 5 static const char *env_vars[NUM_VARS] = { "HOME", "HOMEDRIVE", "HOMEPATH", "USERPROFILE", "PROGRAMFILES" }; #else #define NUM_VARS 1 static const char *env_vars[NUM_VARS] = { "HOME" }; #endif static char *env_save[NUM_VARS]; static char *home_values[] = { "fake_home", "f\xc3\xa1ke_h\xc3\xb5me", /* all in latin-1 supplement */ "f\xc4\x80ke_\xc4\xa4ome", /* latin extended */ "f\xce\xb1\xce\xba\xce\xb5_h\xce\xbfm\xce\xad", /* having fun with greek */ "fa\xe0" "\xb8" "\x87" "e_\xe0" "\xb8" "\x99" "ome", /* thai characters */ "f\xe1\x9c\x80ke_\xe1\x9c\x91ome", /* tagalog characters */ "\xe1\xb8\x9f\xe1\xba\xa2" "ke_ho" "\xe1" "\xb9" "\x81" "e", /* latin extended additional */ "\xf0\x9f\x98\x98\xf0\x9f\x98\x82", /* emoticons */ NULL }; void test_core_env__initialize(void) { int i; for (i = 0; i < NUM_VARS; ++i) env_save[i] = cl_getenv(env_vars[i]); } static void set_global_search_path_from_env(void) { cl_git_pass(git_sysdir_set(GIT_SYSDIR_GLOBAL, NULL)); } static void set_system_search_path_from_env(void) { cl_git_pass(git_sysdir_set(GIT_SYSDIR_SYSTEM, NULL)); } void test_core_env__cleanup(void) { int i; char **val; for (i = 0; i < NUM_VARS; ++i) { cl_setenv(env_vars[i], env_save[i]); git__free(env_save[i]); env_save[i] = NULL; } /* these will probably have already been cleaned up, but if a test * fails, then it's probably good to try and clear out these dirs */ for (val = home_values; *val != NULL; val++) { if (**val != '\0') (void)p_rmdir(*val); } cl_sandbox_set_search_path_defaults(); } static void setenv_and_check(const char *name, const char *value) { char *check; cl_git_pass(cl_setenv(name, value)); check = cl_getenv(name); if (value) cl_assert_equal_s(value, check); else cl_assert(check == NULL); git__free(check); } void test_core_env__0(void) { git_str path = GIT_STR_INIT, found = GIT_STR_INIT; char testfile[16], tidx = '0'; char **val; const char *testname = "testfile"; size_t testlen = strlen(testname); strncpy(testfile, testname, sizeof(testfile)); cl_assert_equal_s(testname, testfile); for (val = home_values; *val != NULL; val++) { /* if we can't make the directory, let's just assume * we are on a filesystem that doesn't support the * characters in question and skip this test... */ if (p_mkdir(*val, 0777) != 0) { *val = ""; /* mark as not created */ continue; } cl_git_pass(git_fs_path_prettify(&path, *val, NULL)); /* vary testfile name in each directory so accidentally leaving * an environment variable set from a previous iteration won't * accidentally make this test pass... */ testfile[testlen] = tidx++; cl_git_pass(git_str_joinpath(&path, path.ptr, testfile)); cl_git_mkfile(path.ptr, "find me"); git_str_rtruncate_at_char(&path, '/'); cl_assert_equal_i( GIT_ENOTFOUND, git_sysdir_find_global_file(&found, testfile)); setenv_and_check("HOME", path.ptr); set_global_search_path_from_env(); cl_git_pass(git_sysdir_find_global_file(&found, testfile)); cl_setenv("HOME", env_save[0]); set_global_search_path_from_env(); cl_assert_equal_i( GIT_ENOTFOUND, git_sysdir_find_global_file(&found, testfile)); #ifdef GIT_WIN32 setenv_and_check("HOMEDRIVE", NULL); setenv_and_check("HOMEPATH", NULL); setenv_and_check("USERPROFILE", path.ptr); set_global_search_path_from_env(); cl_git_pass(git_sysdir_find_global_file(&found, testfile)); { int root = git_fs_path_root(path.ptr); char old; if (root >= 0) { setenv_and_check("USERPROFILE", NULL); set_global_search_path_from_env(); cl_assert_equal_i( GIT_ENOTFOUND, git_sysdir_find_global_file(&found, testfile)); old = path.ptr[root]; path.ptr[root] = '\0'; setenv_and_check("HOMEDRIVE", path.ptr); path.ptr[root] = old; setenv_and_check("HOMEPATH", &path.ptr[root]); set_global_search_path_from_env(); cl_git_pass(git_sysdir_find_global_file(&found, testfile)); } } #endif (void)p_rmdir(*val); } git_str_dispose(&path); git_str_dispose(&found); } void test_core_env__1(void) { git_str path = GIT_STR_INIT; cl_assert_equal_i( GIT_ENOTFOUND, git_sysdir_find_global_file(&path, "nonexistentfile")); cl_git_pass(cl_setenv("HOME", "doesnotexist")); #ifdef GIT_WIN32 cl_git_pass(cl_setenv("HOMEPATH", "doesnotexist")); cl_git_pass(cl_setenv("USERPROFILE", "doesnotexist")); #endif set_global_search_path_from_env(); cl_assert_equal_i( GIT_ENOTFOUND, git_sysdir_find_global_file(&path, "nonexistentfile")); cl_git_pass(cl_setenv("HOME", NULL)); #ifdef GIT_WIN32 cl_git_pass(cl_setenv("HOMEPATH", NULL)); cl_git_pass(cl_setenv("USERPROFILE", NULL)); #endif set_global_search_path_from_env(); set_system_search_path_from_env(); cl_assert_equal_i( GIT_ENOTFOUND, git_sysdir_find_global_file(&path, "nonexistentfile")); cl_assert_equal_i( GIT_ENOTFOUND, git_sysdir_find_system_file(&path, "nonexistentfile")); #ifdef GIT_WIN32 cl_git_pass(cl_setenv("PROGRAMFILES", NULL)); set_system_search_path_from_env(); cl_assert_equal_i( GIT_ENOTFOUND, git_sysdir_find_system_file(&path, "nonexistentfile")); #endif git_str_dispose(&path); } static void check_global_searchpath( const char *path, int position, const char *file, git_str *temp) { git_str out = GIT_STR_INIT; /* build and set new path */ if (position < 0) cl_git_pass(git_str_join(temp, GIT_PATH_LIST_SEPARATOR, path, "$PATH")); else if (position > 0) cl_git_pass(git_str_join(temp, GIT_PATH_LIST_SEPARATOR, "$PATH", path)); else cl_git_pass(git_str_sets(temp, path)); cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, temp->ptr)); /* get path and make sure $PATH expansion worked */ cl_git_pass(git_libgit2_opts( GIT_OPT_GET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, &out)); if (position < 0) cl_assert(git__prefixcmp(out.ptr, path) == 0); else if (position > 0) cl_assert(git__suffixcmp(out.ptr, path) == 0); else cl_assert_equal_s(out.ptr, path); /* find file using new path */ cl_git_pass(git_sysdir_find_global_file(temp, file)); /* reset path and confirm file not found */ cl_git_pass(git_libgit2_opts( GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, NULL)); cl_assert_equal_i( GIT_ENOTFOUND, git_sysdir_find_global_file(temp, file)); git_str_dispose(&out); } void test_core_env__2(void) { git_str path = GIT_STR_INIT, found = GIT_STR_INIT; char testfile[16], tidx = '0'; char **val; const char *testname = "alternate"; size_t testlen = strlen(testname); strncpy(testfile, testname, sizeof(testfile)); cl_assert_equal_s(testname, testfile); for (val = home_values; *val != NULL; val++) { /* if we can't make the directory, let's just assume * we are on a filesystem that doesn't support the * characters in question and skip this test... */ if (p_mkdir(*val, 0777) != 0 && errno != EEXIST) { *val = ""; /* mark as not created */ continue; } cl_git_pass(git_fs_path_prettify(&path, *val, NULL)); /* vary testfile name so any sloppiness is resetting variables or * deleting files won't accidentally make a test pass. */ testfile[testlen] = tidx++; cl_git_pass(git_str_joinpath(&path, path.ptr, testfile)); cl_git_mkfile(path.ptr, "find me"); git_str_rtruncate_at_char(&path, '/'); /* default should be NOTFOUND */ cl_assert_equal_i( GIT_ENOTFOUND, git_sysdir_find_global_file(&found, testfile)); /* try plain, append $PATH, and prepend $PATH */ check_global_searchpath(path.ptr, 0, testfile, &found); check_global_searchpath(path.ptr, -1, testfile, &found); check_global_searchpath(path.ptr, 1, testfile, &found); /* cleanup */ cl_git_pass(git_str_joinpath(&path, path.ptr, testfile)); (void)p_unlink(path.ptr); (void)p_rmdir(*val); } git_str_dispose(&path); git_str_dispose(&found); } void test_core_env__substitution(void) { git_str buf = GIT_STR_INIT, expected = GIT_STR_INIT; /* Set it to something non-default so we have controllable values */ cl_git_pass(git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, "/tmp/a")); cl_git_pass(git_libgit2_opts(GIT_OPT_GET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, &buf)); cl_assert_equal_s("/tmp/a", buf.ptr); git_str_clear(&buf); cl_git_pass(git_str_join(&buf, GIT_PATH_LIST_SEPARATOR, "$PATH", "/tmp/b")); cl_git_pass(git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, buf.ptr)); cl_git_pass(git_libgit2_opts(GIT_OPT_GET_SEARCH_PATH, GIT_CONFIG_LEVEL_GLOBAL, &buf)); cl_git_pass(git_str_join(&expected, GIT_PATH_LIST_SEPARATOR, "/tmp/a", "/tmp/b")); cl_assert_equal_s(expected.ptr, buf.ptr); git_str_dispose(&expected); git_str_dispose(&buf); }
libgit2-main
tests/libgit2/core/env.c
#include "clar_libgit2.h" #include "oid.h" static git_oid id_sha1; static git_oid idp_sha1; static git_oid idm_sha1; const char *str_oid_sha1 = "ae90f12eea699729ed24555e40b9fd669da12a12"; const char *str_oid_sha1_p = "ae90f12eea699729ed"; const char *str_oid_sha1_m = "ae90f12eea699729ed24555e40b9fd669da12a12THIS IS EXTRA TEXT THAT SHOULD GET IGNORED"; #ifdef GIT_EXPERIMENTAL_SHA256 static git_oid id_sha256; static git_oid idp_sha256; static git_oid idm_sha256; const char *str_oid_sha256 = "d3e63d2f2e43d1fee23a74bf19a0ede156cba2d1bd602eba13de433cea1bb512"; const char *str_oid_sha256_p = "d3e63d2f2e43d1fee2"; const char *str_oid_sha256_m = "d3e63d2f2e43d1fee23a74bf19a0ede156cba2d1bd602eba13de433cea1bb512 GARBAGE EXTRA TEXT AT THE END"; #endif void test_core_oid__initialize(void) { cl_git_pass(git_oid__fromstr(&id_sha1, str_oid_sha1, GIT_OID_SHA1)); cl_git_pass(git_oid__fromstrp(&idp_sha1, str_oid_sha1_p, GIT_OID_SHA1)); cl_git_fail(git_oid__fromstrp(&idm_sha1, str_oid_sha1_m, GIT_OID_SHA1)); #ifdef GIT_EXPERIMENTAL_SHA256 cl_git_pass(git_oid__fromstr(&id_sha256, str_oid_sha256, GIT_OID_SHA256)); cl_git_pass(git_oid__fromstrp(&idp_sha256, str_oid_sha256_p, GIT_OID_SHA256)); cl_git_fail(git_oid__fromstrp(&idm_sha256, str_oid_sha256_m, GIT_OID_SHA256)); #endif } void test_core_oid__streq_sha1(void) { cl_assert_equal_i(0, git_oid_streq(&id_sha1, str_oid_sha1)); cl_assert_equal_i(-1, git_oid_streq(&id_sha1, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")); cl_assert_equal_i(-1, git_oid_streq(&id_sha1, "deadbeef")); cl_assert_equal_i(-1, git_oid_streq(&id_sha1, "I'm not an oid.... :)")); cl_assert_equal_i(0, git_oid_streq(&idp_sha1, "ae90f12eea699729ed0000000000000000000000")); cl_assert_equal_i(0, git_oid_streq(&idp_sha1, "ae90f12eea699729ed")); cl_assert_equal_i(-1, git_oid_streq(&idp_sha1, "ae90f12eea699729ed1")); cl_assert_equal_i(-1, git_oid_streq(&idp_sha1, "ae90f12eea699729ec")); cl_assert_equal_i(-1, git_oid_streq(&idp_sha1, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")); cl_assert_equal_i(-1, git_oid_streq(&idp_sha1, "deadbeef")); cl_assert_equal_i(-1, git_oid_streq(&idp_sha1, "I'm not an oid.... :)")); } void test_core_oid__streq_sha256(void) { #ifdef GIT_EXPERIMENTAL_SHA256 cl_assert_equal_i(0, git_oid_streq(&id_sha256, str_oid_sha256)); cl_assert_equal_i(-1, git_oid_streq(&id_sha256, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")); cl_assert_equal_i(-1, git_oid_streq(&id_sha256, "deadbeef")); cl_assert_equal_i(-1, git_oid_streq(&id_sha256, "I'm not an oid.... :)")); cl_assert_equal_i(0, git_oid_streq(&idp_sha256, "d3e63d2f2e43d1fee20000000000000000000000000000000000000000000000")); cl_assert_equal_i(0, git_oid_streq(&idp_sha256, "d3e63d2f2e43d1fee2")); cl_assert_equal_i(-1, git_oid_streq(&idp_sha1, "d3e63d2f2e43d1fee21")); cl_assert_equal_i(-1, git_oid_streq(&idp_sha1, "d3e63d2f2e43d1fee1")); cl_assert_equal_i(-1, git_oid_streq(&idp_sha256, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")); cl_assert_equal_i(-1, git_oid_streq(&idp_sha1, "deadbeef")); cl_assert_equal_i(-1, git_oid_streq(&idp_sha1, "I'm not an oid.... :)")); #endif } void test_core_oid__strcmp_sha1(void) { cl_assert_equal_i(0, git_oid_strcmp(&id_sha1, str_oid_sha1)); cl_assert(git_oid_strcmp(&id_sha1, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef") < 0); cl_assert(git_oid_strcmp(&id_sha1, "deadbeef") < 0); cl_assert_equal_i(-1, git_oid_strcmp(&id_sha1, "I'm not an oid.... :)")); cl_assert_equal_i(0, git_oid_strcmp(&idp_sha1, "ae90f12eea699729ed0000000000000000000000")); cl_assert_equal_i(0, git_oid_strcmp(&idp_sha1, "ae90f12eea699729ed")); cl_assert(git_oid_strcmp(&idp_sha1, "ae90f12eea699729ed1") < 0); cl_assert(git_oid_strcmp(&idp_sha1, "ae90f12eea699729ec") > 0); cl_assert(git_oid_strcmp(&idp_sha1, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef") < 0); cl_assert(git_oid_strcmp(&idp_sha1, "deadbeef") < 0); cl_assert_equal_i(-1, git_oid_strcmp(&idp_sha1, "I'm not an oid.... :)")); } void test_core_oid__strcmp_sha256(void) { #ifdef GIT_EXPERIMENTAL_SHA256 cl_assert_equal_i(0, git_oid_strcmp(&id_sha256, str_oid_sha256)); cl_assert(git_oid_strcmp(&id_sha256, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef") < 0); cl_assert(git_oid_strcmp(&id_sha256, "deadbeef") < 0); cl_assert_equal_i(-1, git_oid_strcmp(&id_sha256, "I'm not an oid.... :)")); cl_assert_equal_i(0, git_oid_strcmp(&idp_sha256, "d3e63d2f2e43d1fee20000000000000000000000")); cl_assert_equal_i(0, git_oid_strcmp(&idp_sha256, "d3e63d2f2e43d1fee2")); cl_assert(git_oid_strcmp(&idp_sha256, "d3e63d2f2e43d1fee21") < 0); cl_assert(git_oid_strcmp(&idp_sha256, "d3e63d2f2e43d1fee1") > 0); cl_assert(git_oid_strcmp(&idp_sha256, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef") < 0); cl_assert(git_oid_strcmp(&idp_sha256, "deadbeef") < 0); cl_assert_equal_i(-1, git_oid_strcmp(&idp_sha256, "I'm not an oid.... :)")); #endif } void test_core_oid__ncmp_sha1(void) { cl_assert(!git_oid_ncmp(&id_sha1, &idp_sha1, 0)); cl_assert(!git_oid_ncmp(&id_sha1, &idp_sha1, 1)); cl_assert(!git_oid_ncmp(&id_sha1, &idp_sha1, 2)); cl_assert(!git_oid_ncmp(&id_sha1, &idp_sha1, 17)); cl_assert(!git_oid_ncmp(&id_sha1, &idp_sha1, 18)); cl_assert(git_oid_ncmp(&id_sha1, &idp_sha1, 19)); cl_assert(git_oid_ncmp(&id_sha1, &idp_sha1, 40)); cl_assert(git_oid_ncmp(&id_sha1, &idp_sha1, 41)); cl_assert(git_oid_ncmp(&id_sha1, &idp_sha1, 42)); cl_assert(!git_oid_ncmp(&id_sha1, &id_sha1, 0)); cl_assert(!git_oid_ncmp(&id_sha1, &id_sha1, 1)); cl_assert(!git_oid_ncmp(&id_sha1, &id_sha1, 39)); cl_assert(!git_oid_ncmp(&id_sha1, &id_sha1, 40)); cl_assert(!git_oid_ncmp(&id_sha1, &id_sha1, 41)); } void test_core_oid__ncmp_sha256(void) { #ifdef GIT_EXPERIMENTAL_SHA256 cl_assert(!git_oid_ncmp(&id_sha256, &idp_sha256, 0)); cl_assert(!git_oid_ncmp(&id_sha256, &idp_sha256, 1)); cl_assert(!git_oid_ncmp(&id_sha256, &idp_sha256, 2)); cl_assert(!git_oid_ncmp(&id_sha256, &idp_sha256, 17)); cl_assert(!git_oid_ncmp(&id_sha256, &idp_sha256, 18)); cl_assert(git_oid_ncmp(&id_sha256, &idp_sha256, 19)); cl_assert(git_oid_ncmp(&id_sha256, &idp_sha256, 40)); cl_assert(git_oid_ncmp(&id_sha256, &idp_sha256, 41)); cl_assert(git_oid_ncmp(&id_sha256, &idp_sha256, 42)); cl_assert(git_oid_ncmp(&id_sha256, &idp_sha256, 63)); cl_assert(git_oid_ncmp(&id_sha256, &idp_sha256, 64)); cl_assert(git_oid_ncmp(&id_sha256, &idp_sha256, 65)); cl_assert(!git_oid_ncmp(&id_sha256, &id_sha256, 0)); cl_assert(!git_oid_ncmp(&id_sha256, &id_sha256, 1)); cl_assert(!git_oid_ncmp(&id_sha256, &id_sha256, 39)); cl_assert(!git_oid_ncmp(&id_sha256, &id_sha256, 40)); cl_assert(!git_oid_ncmp(&id_sha256, &id_sha256, 41)); cl_assert(!git_oid_ncmp(&id_sha256, &id_sha256, 63)); cl_assert(!git_oid_ncmp(&id_sha256, &id_sha256, 64)); cl_assert(!git_oid_ncmp(&id_sha256, &id_sha256, 65)); #endif } void test_core_oid__is_hexstr(void) { cl_assert(git_oid__is_hexstr("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef", GIT_OID_SHA1)); cl_assert(!git_oid__is_hexstr("deadbeefdeadbeef", GIT_OID_SHA1)); cl_assert(!git_oid__is_hexstr("zeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", GIT_OID_SHA1)); cl_assert(!git_oid__is_hexstr("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef1", GIT_OID_SHA1)); } void test_core_oid__fmt_substr_sha1(void) { char buf[GIT_OID_MAX_HEXSIZE + 1]; memset(buf, 0, GIT_OID_MAX_HEXSIZE + 1); git_oid_fmt_substr(buf, &id_sha1, 0, 40); cl_assert_equal_s(buf, str_oid_sha1); memset(buf, 0, GIT_OID_MAX_HEXSIZE + 1); git_oid_fmt_substr(buf, &id_sha1, 0, 18); cl_assert_equal_s(buf, str_oid_sha1_p); memset(buf, 0, GIT_OID_MAX_HEXSIZE + 1); git_oid_fmt_substr(buf, &id_sha1, 0, 5); cl_assert_equal_s(buf, "ae90f"); memset(buf, 0, GIT_OID_MAX_HEXSIZE + 1); git_oid_fmt_substr(buf, &id_sha1, 5, 5); cl_assert_equal_s(buf, "12eea"); memset(buf, 0, GIT_OID_MAX_HEXSIZE + 1); git_oid_fmt_substr(buf, &id_sha1, 5, 6); cl_assert_equal_s(buf, "12eea6"); }
libgit2-main
tests/libgit2/core/oid.c
#include "clar_libgit2.h" void test_core_features__0(void) { int major, minor, rev, caps; git_libgit2_version(&major, &minor, &rev); cl_assert_equal_i(LIBGIT2_VER_MAJOR, major); cl_assert_equal_i(LIBGIT2_VER_MINOR, minor); cl_assert_equal_i(LIBGIT2_VER_REVISION, rev); caps = git_libgit2_features(); #ifdef GIT_THREADS cl_assert((caps & GIT_FEATURE_THREADS) != 0); #else cl_assert((caps & GIT_FEATURE_THREADS) == 0); #endif #ifdef GIT_HTTPS cl_assert((caps & GIT_FEATURE_HTTPS) != 0); #endif #if defined(GIT_SSH) cl_assert((caps & GIT_FEATURE_SSH) != 0); #else cl_assert((caps & GIT_FEATURE_SSH) == 0); #endif #if defined(GIT_USE_NSEC) cl_assert((caps & GIT_FEATURE_NSEC) != 0); #else cl_assert((caps & GIT_FEATURE_NSEC) == 0); #endif }
libgit2-main
tests/libgit2/core/features.c
#include "clar_libgit2.h" #include "cache.h" void test_core_opts__cleanup(void) { cl_git_pass(git_libgit2_opts(GIT_OPT_SET_EXTENSIONS, NULL, 0)); } void test_core_opts__readwrite(void) { size_t old_val = 0; size_t new_val = 0; git_libgit2_opts(GIT_OPT_GET_MWINDOW_SIZE, &old_val); git_libgit2_opts(GIT_OPT_SET_MWINDOW_SIZE, (size_t)1234); git_libgit2_opts(GIT_OPT_GET_MWINDOW_SIZE, &new_val); cl_assert(new_val == 1234); git_libgit2_opts(GIT_OPT_SET_MWINDOW_SIZE, old_val); git_libgit2_opts(GIT_OPT_GET_MWINDOW_SIZE, &new_val); cl_assert(new_val == old_val); } void test_core_opts__invalid_option(void) { cl_git_fail(git_libgit2_opts(-1, "foobar")); } void test_core_opts__extensions_query(void) { git_strarray out = { 0 }; cl_git_pass(git_libgit2_opts(GIT_OPT_GET_EXTENSIONS, &out)); cl_assert_equal_sz(out.count, 1); cl_assert_equal_s("noop", out.strings[0]); git_strarray_dispose(&out); } void test_core_opts__extensions_add(void) { const char *in[] = { "foo" }; git_strarray out = { 0 }; cl_git_pass(git_libgit2_opts(GIT_OPT_SET_EXTENSIONS, in, ARRAY_SIZE(in))); cl_git_pass(git_libgit2_opts(GIT_OPT_GET_EXTENSIONS, &out)); cl_assert_equal_sz(out.count, 2); cl_assert_equal_s("noop", out.strings[0]); cl_assert_equal_s("foo", out.strings[1]); git_strarray_dispose(&out); } void test_core_opts__extensions_remove(void) { const char *in[] = { "bar", "!negate", "!noop", "baz" }; git_strarray out = { 0 }; cl_git_pass(git_libgit2_opts(GIT_OPT_SET_EXTENSIONS, in, ARRAY_SIZE(in))); cl_git_pass(git_libgit2_opts(GIT_OPT_GET_EXTENSIONS, &out)); cl_assert_equal_sz(out.count, 2); cl_assert_equal_s("bar", out.strings[0]); cl_assert_equal_s("baz", out.strings[1]); git_strarray_dispose(&out); }
libgit2-main
tests/libgit2/core/opts.c
#include "clar_libgit2.h" #include "pool.h" #include "git2/oid.h" static char to_hex[] = "0123456789abcdef"; void test_core_pool__oid(void) { git_pool p; char oid_hex[GIT_OID_SHA1_HEXSIZE]; git_oid *oid; int i, j; memset(oid_hex, '0', sizeof(oid_hex)); git_pool_init(&p, sizeof(git_oid)); p.page_size = 4000; for (i = 1000; i < 10000; i++) { oid = git_pool_malloc(&p, 1); cl_assert(oid != NULL); for (j = 0; j < 8; j++) oid_hex[j] = to_hex[(i >> (4 * j)) & 0x0f]; cl_git_pass(git_oid__fromstr(oid, oid_hex, GIT_OID_SHA1)); } #ifndef GIT_DEBUG_POOL /* with fixed page size, allocation must end up with these values */ # ifdef GIT_EXPERIMENTAL_SHA256 cl_assert_equal_i(sizeof(void *) == 8 ? 90 : 82, git_pool__open_pages(&p)); # else cl_assert_equal_i(sizeof(void *) == 8 ? 55 : 45, git_pool__open_pages(&p)); # endif #endif git_pool_clear(&p); }
libgit2-main
tests/libgit2/core/pool.c
#include "clar_libgit2.h" #include <git2/sys/commit_graph.h> #include <git2/sys/config.h> #include <git2/sys/filter.h> #include <git2/sys/odb_backend.h> #include <git2/sys/refdb_backend.h> #include <git2/sys/transport.h> #define STRINGIFY(s) #s /* Checks two conditions for the specified structure: * 1. That the initializers for the latest version produces the same * in-memory representation. * 2. That the function-based initializer supports all versions from 1...n, * where n is the latest version (often represented by GIT_*_VERSION). * * Parameters: * structname: The name of the structure to test, e.g. git_blame_options. * structver: The latest version of the specified structure. * macroinit: The macro that initializes the latest version of the structure. * funcinitname: The function that initializes the structure. Must have the * signature "int (structname* instance, int version)". */ #define CHECK_MACRO_FUNC_INIT_EQUAL(structname, structver, macroinit, funcinitname) \ do { \ structname structname##_macro_latest = macroinit; \ structname structname##_func_latest; \ int structname##_curr_ver = structver - 1; \ memset(&structname##_func_latest, 0, sizeof(structname##_func_latest)); \ cl_git_pass(funcinitname(&structname##_func_latest, structver)); \ options_cmp(&structname##_macro_latest, &structname##_func_latest, \ sizeof(structname), STRINGIFY(structname)); \ \ while (structname##_curr_ver > 0) \ { \ structname macro; \ cl_git_pass(funcinitname(&macro, structname##_curr_ver)); \ structname##_curr_ver--; \ }\ } while(0) static void options_cmp(void *one, void *two, size_t size, const char *name) { size_t i; for (i = 0; i < size; i++) { if (((char *)one)[i] != ((char *)two)[i]) { char desc[1024]; p_snprintf(desc, 1024, "Difference in %s at byte %" PRIuZ ": macro=%u / func=%u", name, i, ((char *)one)[i], ((char *)two)[i]); clar__fail(__FILE__, __func__, __LINE__, "Difference between macro and function options initializer", desc, 0); return; } } } void test_core_structinit__compare(void) { /* These tests assume that they can memcmp() two structures that were * initialized with the same static initializer. Eg, * git_blame_options = GIT_BLAME_OPTIONS_INIT; * * This assumption fails when there is padding between structure members, * which is not guaranteed to be initialized to anything sane at all. * * Assume most compilers, in a debug build, will clear that memory for * us or set it to sentinel markers. Etc. */ #if !defined(DEBUG) && !defined(_DEBUG) clar__skip(); #endif /* apply */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_apply_options, GIT_APPLY_OPTIONS_VERSION, \ GIT_APPLY_OPTIONS_INIT, git_apply_options_init); /* blame */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_blame_options, GIT_BLAME_OPTIONS_VERSION, \ GIT_BLAME_OPTIONS_INIT, git_blame_options_init); /* blob_filter_options */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_blob_filter_options, GIT_BLOB_FILTER_OPTIONS_VERSION, \ GIT_BLOB_FILTER_OPTIONS_INIT, git_blob_filter_options_init); /* checkout */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_checkout_options, GIT_CHECKOUT_OPTIONS_VERSION, \ GIT_CHECKOUT_OPTIONS_INIT, git_checkout_options_init); /* clone */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_clone_options, GIT_CLONE_OPTIONS_VERSION, \ GIT_CLONE_OPTIONS_INIT, git_clone_options_init); /* commit_graph_writer */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_commit_graph_writer_options, \ GIT_COMMIT_GRAPH_WRITER_OPTIONS_VERSION, \ GIT_COMMIT_GRAPH_WRITER_OPTIONS_INIT, \ git_commit_graph_writer_options_init); /* diff */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_diff_options, GIT_DIFF_OPTIONS_VERSION, \ GIT_DIFF_OPTIONS_INIT, git_diff_options_init); /* diff_find */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_diff_find_options, GIT_DIFF_FIND_OPTIONS_VERSION, \ GIT_DIFF_FIND_OPTIONS_INIT, git_diff_find_options_init); /* filter */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_filter, GIT_FILTER_VERSION, \ GIT_FILTER_INIT, git_filter_init); /* merge_file_input */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_merge_file_input, GIT_MERGE_FILE_INPUT_VERSION, \ GIT_MERGE_FILE_INPUT_INIT, git_merge_file_input_init); /* merge_file */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_merge_file_options, GIT_MERGE_FILE_OPTIONS_VERSION, \ GIT_MERGE_FILE_OPTIONS_INIT, git_merge_file_options_init); /* merge_tree */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_merge_options, GIT_MERGE_OPTIONS_VERSION, \ GIT_MERGE_OPTIONS_INIT, git_merge_options_init); /* push */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_push_options, GIT_PUSH_OPTIONS_VERSION, \ GIT_PUSH_OPTIONS_INIT, git_push_options_init); /* remote */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_remote_callbacks, GIT_REMOTE_CALLBACKS_VERSION, \ GIT_REMOTE_CALLBACKS_INIT, git_remote_init_callbacks); /* repository_init */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_repository_init_options, GIT_REPOSITORY_INIT_OPTIONS_VERSION, \ GIT_REPOSITORY_INIT_OPTIONS_INIT, git_repository_init_options_init); /* revert */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_revert_options, GIT_REVERT_OPTIONS_VERSION, \ GIT_REVERT_OPTIONS_INIT, git_revert_options_init); /* stash apply */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_stash_apply_options, GIT_STASH_APPLY_OPTIONS_VERSION, \ GIT_STASH_APPLY_OPTIONS_INIT, git_stash_apply_options_init); /* status */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_status_options, GIT_STATUS_OPTIONS_VERSION, \ GIT_STATUS_OPTIONS_INIT, git_status_options_init); /* transport */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_transport, GIT_TRANSPORT_VERSION, \ GIT_TRANSPORT_INIT, git_transport_init); /* config_backend */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_config_backend, GIT_CONFIG_BACKEND_VERSION, \ GIT_CONFIG_BACKEND_INIT, git_config_init_backend); /* odb_backend */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_odb_backend, GIT_ODB_BACKEND_VERSION, \ GIT_ODB_BACKEND_INIT, git_odb_init_backend); /* refdb_backend */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_refdb_backend, GIT_REFDB_BACKEND_VERSION, \ GIT_REFDB_BACKEND_INIT, git_refdb_init_backend); /* submodule update */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_submodule_update_options, GIT_SUBMODULE_UPDATE_OPTIONS_VERSION, \ GIT_SUBMODULE_UPDATE_OPTIONS_INIT, git_submodule_update_options_init); /* submodule update */ CHECK_MACRO_FUNC_INIT_EQUAL( \ git_proxy_options, GIT_PROXY_OPTIONS_VERSION, \ GIT_PROXY_OPTIONS_INIT, git_proxy_options_init); CHECK_MACRO_FUNC_INIT_EQUAL( \ git_diff_patchid_options, GIT_DIFF_PATCHID_OPTIONS_VERSION, \ GIT_DIFF_PATCHID_OPTIONS_INIT, git_diff_patchid_options_init); }
libgit2-main
tests/libgit2/core/structinit.c
#include "clar_libgit2.h" #include "buf.h" void test_core_buf__sanitize(void) { git_buf buf = { (char *)0x42, 0, 16 }; cl_git_pass(git_buf_sanitize(&buf)); cl_assert_equal_s(buf.ptr, ""); cl_assert_equal_i(buf.reserved, 0); cl_assert_equal_i(buf.size, 0); git_buf_dispose(&buf); } void test_core_buf__tostr(void) { git_str str = GIT_STR_INIT; git_buf buf = { (char *)0x42, 0, 16 }; cl_git_pass(git_buf_tostr(&str, &buf)); cl_assert_equal_s(buf.ptr, ""); cl_assert_equal_i(buf.reserved, 0); cl_assert_equal_i(buf.size, 0); cl_assert_equal_s(str.ptr, ""); cl_assert_equal_i(str.asize, 0); cl_assert_equal_i(str.size, 0); git_buf_dispose(&buf); git_str_dispose(&str); } void test_core_buf__fromstr(void) { git_str str = GIT_STR_INIT; git_buf buf = { (char *)0x42, 0, 16 }; cl_git_pass(git_buf_tostr(&str, &buf)); cl_git_pass(git_str_puts(&str, "Hello, world.")); cl_git_pass(git_buf_fromstr(&buf, &str)); cl_assert(buf.reserved > 14); cl_assert_equal_i(buf.size, 13); cl_assert_equal_s(buf.ptr, "Hello, world."); cl_assert_equal_s(str.ptr, ""); cl_assert_equal_i(str.asize, 0); cl_assert_equal_i(str.size, 0); git_buf_dispose(&buf); git_str_dispose(&str); }
libgit2-main
tests/libgit2/core/buf.c
#include "clar.h" #include "clar_libgit2.h" #include "futils.h" #include "git2/cherrypick.h" #include "../merge/merge_helpers.h" #define TEST_REPO_PATH "cherrypick" static git_repository *repo; void test_cherrypick_bare__initialize(void) { repo = cl_git_sandbox_init(TEST_REPO_PATH); } void test_cherrypick_bare__cleanup(void) { cl_git_sandbox_cleanup(); } void test_cherrypick_bare__automerge(void) { git_commit *head = NULL, *commit = NULL; git_index *index = NULL; git_oid head_oid, cherry_oid; struct merge_index_entry merge_index_entries[] = { { 0100644, "38c05a857e831a7e759d83778bfc85d003e21c45", 0, "file1.txt" }, { 0100644, "a661b5dec1004e2c62654ded3762370c27cf266b", 0, "file2.txt" }, { 0100644, "df6b290e0bd6a89b01d69f66687e8abf385283ca", 0, "file3.txt" }, }; git_oid__fromstr(&head_oid, "d3d77487660ee3c0194ee01dc5eaf478782b1c7e", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); git_oid__fromstr(&cherry_oid, "cfc4f0999a8367568e049af4f72e452d40828a15", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &cherry_oid)); cl_git_pass(git_cherrypick_commit(&index, repo, commit, head, 0, NULL)); cl_assert(merge_test_index(index, merge_index_entries, 3)); git_index_free(index); git_commit_free(head); git_commit_free(commit); } void test_cherrypick_bare__conflicts(void) { git_commit *head = NULL, *commit = NULL; git_index *index = NULL; git_oid head_oid, cherry_oid; struct merge_index_entry merge_index_entries[] = { { 0100644, "242e7977ba73637822ffb265b46004b9b0e5153b", 0, "file1.txt" }, { 0100644, "a58ca3fee5eb68b11adc2703e5843f968c9dad1e", 1, "file2.txt" }, { 0100644, "bd6ffc8c6c41f0f85ff9e3d61c9479516bac0024", 2, "file2.txt" }, { 0100644, "563f6473a3858f99b80e5f93c660512ed38e1e6f", 3, "file2.txt" }, { 0100644, "28d9eb4208074ad1cc84e71ccc908b34573f05d2", 1, "file3.txt" }, { 0100644, "1124c2c1ae07b26fded662d6c3f3631d9dc16f88", 2, "file3.txt" }, { 0100644, "e233b9ed408a95e9d4b65fec7fc34943a556deb2", 3, "file3.txt" }, }; git_oid__fromstr(&head_oid, "bafbf6912c09505ac60575cd43d3f2aba3bd84d8", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); git_oid__fromstr(&cherry_oid, "e9b63f3655b2ad80c0ff587389b5a9589a3a7110", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &cherry_oid)); cl_git_pass(git_cherrypick_commit(&index, repo, commit, head, 0, NULL)); cl_assert(merge_test_index(index, merge_index_entries, 7)); git_index_free(index); git_commit_free(head); git_commit_free(commit); } void test_cherrypick_bare__orphan(void) { git_commit *head = NULL, *commit = NULL; git_index *index = NULL; git_oid head_oid, cherry_oid; struct merge_index_entry merge_index_entries[] = { { 0100644, "38c05a857e831a7e759d83778bfc85d003e21c45", 0, "file1.txt" }, { 0100644, "a661b5dec1004e2c62654ded3762370c27cf266b", 0, "file2.txt" }, { 0100644, "85a4a1d791973644f24c72f5e89420d3064cc452", 0, "file3.txt" }, { 0100644, "9ccb9bf50c011fd58dcbaa65df917bf79539717f", 0, "orphan.txt" }, }; git_oid__fromstr(&head_oid, "d3d77487660ee3c0194ee01dc5eaf478782b1c7e", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&head, repo, &head_oid)); git_oid__fromstr(&cherry_oid, "74f06b5bfec6d33d7264f73606b57a7c0b963819", GIT_OID_SHA1); cl_git_pass(git_commit_lookup(&commit, repo, &cherry_oid)); cl_git_pass(git_cherrypick_commit(&index, repo, commit, head, 0, NULL)); cl_assert(merge_test_index(index, merge_index_entries, 4)); git_index_free(index); git_commit_free(head); git_commit_free(commit); }
libgit2-main
tests/libgit2/cherrypick/bare.c