how to use libgit2 to fetch from the git? - libgit2

I read the fetch.c and try to update the content in local repository(just like "git fetch"), but git_remote_connect return -1.
err:Unexpected HTTP status code: 401
where to set the cred when connect to the remote? What is wrong with the code?? Thx.
(IBAction)Fetch:(id)sender {
git_remote *remote = NULL;
const git_error *err = NULL;
int ret = -1;
bool invoked = false;
git_repository *repo = NULL;
NSArray *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [str objectAtIndex:0];
NSString *localPath = [docPath stringByAppendingPathComponent:#"abc/.git"];
NSLog(#"localPath:%#", localPath);
ret = git_repository_open(&repo, [localPath UTF8String]);
NSLog(#"git_repository_open ret:%d",ret);
err = giterr_last();
if(err == NULL)
{
NSLog(#"NULL");
}
else
{
NSLog(#"err:%s", err->message);
}
ret = git_remote_load(&remote, repo, "origin");
NSLog(#"git_remote_load ret:%d", ret);
err = giterr_last();
if(err == NULL)
{
NSLog(#"No error");
}
else
{
NSLog(#"err:%s", err->message);
return;
}
ret = git_remote_load(&remote, repo, "origin");
NSLog(#"git_remote_load ret:%d", ret);
ret = git_remote_connect(remote, GIT_DIRECTION_FETCH);
NSLog(#"git_remote_connect ret:%d", ret);
err = giterr_last();
if(err == NULL)
{
NSLog(#"No error");
}
else
{
NSLog(#"err:%s", err->message);
return;
}
ret = git_remote_download(remote, &transferProgressCallback, &invoked);
NSLog(#"git_remote_download ret:%d", ret);
err = giterr_last();
if(err == NULL)
{
NSLog(#"No error");
}
else
{
NSLog(#"err:%s", err->message);
return;
}
ret = git_remote_update_tips(remote);
NSLog(#"git_remote_update_tips ret:%d", ret);
err = giterr_last();
if(err == NULL)
{
NSLog(#"No error");
}
else
{
NSLog(#"err:%s", err->message);
return;
}
}
here is the remote config
[remote "origin"]
url = http://remote_path/git/share.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master

I find the function below to set cred which the remote acquire
bool invoked = false;
git_remote_set_cred_acquire_cb(remote, cred_acquire_cb, &invoked);
The code of cred_acquire_cb is below:
static int cred_acquire_cb(git_cred **cred, const char *url, unsigned int allowed_types, void *payload)
{
char *_remote_user = "user";
char *_remote_pass = "pass";
*((bool*)payload) = true;
if ((GIT_CREDTYPE_USERPASS_PLAINTEXT & allowed_types) == 0 ||
git_cred_userpass_plaintext_new(cred, _remote_user, _remote_pass) < 0)
return -1;
return 0;
}

Related

Why is the deleted file commit by default when using the commit command in libgit2?

I delete the file: user git_remove_bypath and git_index_write
I use the index to commit, and don't commit the file by removed file,but the file by my removed also commit success.
int commit(void *repository, const char *file_name[], const unsigned int file, const char *message, void *payload)
{
int error = -1;
git_signature *signature = NULL;
/*git git; identify of any object*/
/*git commit_id; identify of any object*/
void* index = NULL;
void* tree = NULL;
do /* try catch */
{
const char *path = git_repository_path((git_repository*)repository);
/*get signature*/
error = git_signature_default(&signature, (git_repository*)repository);
/*get repository head*/
error = git_repository_head(&ref_head,(git_repository*)repository);
if (error == GIT_OK)
{
error = git_commit_lookup(&parent_commit, (git_repository*)repository, git_reference_target(ref_head));
}
else if (error != -9)
{
break;
}
/*get repository index*/
error = git_repository_index((git_index**)&index, (git_repository*)repository);
for(int i = 0; i < Count; ++i)
{
/*get statue*/
error = git_status_file(&flags, (git_repository *)repository, file_name[i]);
if(-3 == error || -5 == error)
{
continue;
}
if( GIT_STATUS_INDEX_DELETED & flags || GIT_STATUS_WT_DELETED & flags )
{
/*remove file*/
error = git_index_remove_bypath((git_index *)index, file_name[i]);
}
else
{
/*add file*/
error = git_index_add_bypath((git_index *)index, file_name[i]);
}
/*write disk*/
error = git_index_write((git_index*)index);
}
/* Get the index and write it to a tree */
error = git_index_write_tree(&git, (git_index*)index);
/* lookup tree */
error = git_tree_lookup((git_tree**)&tree, (git_repository *)repository, &git);
/* Do the commit*/
error = git_commit_create(&commit_id, (git_repository*)repository, "HEAD", signature, signature, NULL,
message, (git_tree *)tree, 1, parents);
}while(0);
}

Why does my structure assignment fail in C language?

Why does my structure assignment fail in C language?
I have a class A: define a structure
typedef struct{
int sockfd;
on_av_frame_cb av_frame_cb;
on_av_frame_cb rtp_cb;
on_error_cb error_cb;
uint8_t *p_buf;
uint8_t *v_buf;
uint8_t *a_buf;
int rtp_flag;
}udp_client_t;
Then I call in class B:
static udp_client_t client;
int jldv_create_client(int src_port,int port ,const char *dst_ip){
udp_client_t *udpClient = &client;
assert(udpClient != NULL);
const char *c_ip = dst_ip;
memset(udpClient, 0, sizeof(udp_client_t));
int ret = create_client(src_port, port, c_ip, &udpClient);
if (ret != 0) {
goto err_output;
}
udpClient->av_frame_cb = (on_av_frame_cb )onVideoFrame;
udpClient->error_cb = on_error;
if (rtp_create(&udpClient) < 0) { ///above problem
goto err_output;
}
printf("rtp_client:%d \n",udpClient->rtp_flag);
return 0;
err_output:
destroy_client(udpClient);
return -1;
}
In the above problem, I used the C class method:
int rtp_create(udp_client_t **data)
{
logi("%s", __func__);
udp_client_t *udpClient = *data;
if(udpClient)
{
udpClient->rtp_flag = 1;
memset(&rtp_cxt, 0, sizeof(rtp_context_t));
int ret = init_server();
if (ret < 0)
{
return -1;
}
rtp_cxt.nalu = alloc_nalu(MAX_FRAME_SIZE);//
if (!rtp_cxt.nalu)
{
loge("alloc nalu failed");
return -2;
}
}
else
{
loge("%s: data is null", __func__);
return -3;
}
printf("udpClient after==>%d \n",udpClient->rtp_flag);
return 0;
}
However, the result of printing is:
udpClient after==>1
rtp_client:0
supplement:
int create_client(int src_port, int dst_port, const char *dst_ip, udp_client_t **client)
{
udp_client_t *udpClient = *client;
assert(udpClient != NULL);
memset(udpClient, 0, sizeof(udp_client_t));
printf("create_client:%p\n",udpClient);
udpClient->port = src_port;
if (pthread_create(&udpClient->recv_tid, NULL, udp_receiver_runnable, (void *) udpClient) != 0)
{
loge("Failed to start new thread");
goto err_output;
}
return 0;
err_output:
memset(udpClient, 0, sizeof(udp_client_t));
return -10;
}
Why is that? Did i use something wrong?

How do I recursively copy a directory using vala?

I'm new to Vala, so this may be a stupid question.
According to #vala on gimpnet, it is not possible to recursively copy directories using Glib.File.copy. At the moment I am using:
Posix.system("cp -r absolutesource absolutedestination")
Is there a better method of doing this?
As I told you in IRC, you can just write a function to do it yourself by calling GLib.File.copy for each file you want to copy. Here is a basic example:
public bool copy_recursive (GLib.File src, GLib.File dest, GLib.FileCopyFlags flags = GLib.FileCopyFlags.NONE, GLib.Cancellable? cancellable = null) throws GLib.Error {
GLib.FileType src_type = src.query_file_type (GLib.FileQueryInfoFlags.NONE, cancellable);
if ( src_type == GLib.FileType.DIRECTORY ) {
dest.make_directory (cancellable);
src.copy_attributes (dest, flags, cancellable);
string src_path = src.get_path ();
string dest_path = dest.get_path ();
GLib.FileEnumerator enumerator = src.enumerate_children (GLib.FileAttribute.STANDARD_NAME, GLib.FileQueryInfoFlags.NONE, cancellable);
for ( GLib.FileInfo? info = enumerator.next_file (cancellable) ; info != null ; info = enumerator.next_file (cancellable) ) {
copy_recursive (
GLib.File.new_for_path (GLib.Path.build_filename (src_path, info.get_name ())),
GLib.File.new_for_path (GLib.Path.build_filename (dest_path, info.get_name ())),
flags,
cancellable);
}
} else if ( src_type == GLib.FileType.REGULAR ) {
src.copy (dest, flags, cancellable);
}
return true;
}
Also, it's worth noting that you might want to use one of the functions in GLib.Process instead of Posix.system.
I came across this question looking for something similar in C using GLib/GIO.
Here's my attempt at converting the C++ code above to C
gboolean
copy_recursive(GFile *src, GFile *dest, GFileCopyFlags flags, GCancellable *cancellable, GError **error) {
GFileType src_type = g_file_query_file_type(src, G_FILE_QUERY_INFO_NONE, cancellable);
if (src_type == G_FILE_TYPE_DIRECTORY) {
g_file_make_directory(dest, cancellable, error);
g_file_copy_attributes(src, dest, flags, cancellable, error);
GFileEnumerator *enumerator = g_file_enumerate_children(src, G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NONE, cancellable, error);
for (GFileInfo *info = g_file_enumerator_next_file(enumerator, cancellable, error); info != NULL; info = g_file_enumerator_next_file(enumerator, cancellable, error)) {
const char *relative_path = g_file_info_get_name(info);
copy_recursive(
g_file_resolve_relative_path(src, relative_path),
g_file_resolve_relative_path(dest, relative_path),
flags, cancellable, error);
}
} else if (src_type == G_FILE_TYPE_REGULAR) {
g_file_copy(src, dest, flags, cancellable, NULL, NULL, error);
}
return TRUE;
}
As a bonus, here's a function that recursively deletes a directory
gboolean
delete_recursive(GFile *file, GCancellable *cancellable, GError **error) {
GFileType file_type = g_file_query_file_type(file, G_FILE_QUERY_INFO_NONE, cancellable);
if (file_type == G_FILE_TYPE_DIRECTORY) {
GFileEnumerator *enumerator = g_file_enumerate_children(file, G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NONE, cancellable, error);
for (GFileInfo *info = g_file_enumerator_next_file(enumerator, cancellable, error); info != NULL; info = g_file_enumerator_next_file(enumerator, cancellable, error)) {
delete_recursive(
g_file_resolve_relative_path(file, g_file_info_get_name(info)),
cancellable, error);
}
g_file_delete(file, cancellable, error);
} else if (file_type == G_FILE_TYPE_REGULAR) {
g_file_delete(file, cancellable, error);
}
return TRUE;
}

SecKeychain load item

I want to store SMTP-Data from my Mac OSX application using the keychain. I read the Keychain Services Programming Guide of Apple and wrote this method to store the data:
- (BOOL)saveSMPTData
{
OSStatus err;
SecKeychainItemRef item = nil;
SecProtocolType protocol = kSecProtocolTypeSMTP;
const char *accessLabelUTF8 = [KEYCHAIN_NAME UTF8String];
const char *serverNameUTF8 = [self.serverName UTF8String];
const char *usernameUTF8 = [self.username UTF8String];
const char *passwordUTF8 = [self.password UTF8String];
SecAccessRef access = createAccess(KEYCHAIN_NAME);
SecKeychainAttribute attrs[] = {
{ kSecLabelItemAttr, (int)strlen(accessLabelUTF8), (char *)accessLabelUTF8 },
{ kSecAccountItemAttr, (int)strlen(usernameUTF8), (char *)usernameUTF8 },
{ kSecServerItemAttr, (int)strlen(serverNameUTF8), (char *)serverNameUTF8 },
{ kSecProtocolItemAttr, sizeof(SecProtocolType), (SecProtocolType *)&protocol }
};
SecKeychainAttributeList attributes = { sizeof(attrs) / sizeof(attrs[0]), attrs };
err = SecKeychainItemCreateFromContent(kSecInternetPasswordItemClass,
&attributes,
(int)strlen(passwordUTF8),
passwordUTF8,
NULL,
access,
&item);
if (access) CFRelease(access);
if (item) CFRelease(item);
return (err == noErr);
}
SecAccessRef createAccess(NSString *accessLabel)
{
OSStatus err;
SecAccessRef access = nil;
NSArray *trustedApplications = nil;
SecTrustedApplicationRef myself;
err = SecTrustedApplicationCreateFromPath(NULL, &myself);
trustedApplications = [NSArray arrayWithObjects:(__bridge id)myself, nil];
err = SecAccessCreate((__bridge CFStringRef)accessLabel,
(__bridge CFArrayRef)trustedApplications, &access);
if (err) return nil;
return access;
}
Of course I also want to load them. My first try looks like this:
- (BOOL)loadDataFromKeychain
{
uint32_t serverNameLength = 0;
const char *serverName = NULL;
uint32_t usernameLength = 0;
const char *username = NULL;
uint32_t passwordLength = 0;
void **password = NULL;
OSStatus err = SecKeychainFindInternetPassword(NULL,
serverNameLength, serverName,
0, NULL,
usernameLength, username,
0, NULL,
0, 0,
0,
&passwordLength, password,
NULL); // How do I get the ItemRef?
return (err == noErr);
}
But this does not work, and I think I know why not. I don’t know how to get the SecKeychainItemRef for the SecKeychainFindInternetPassword method.
Maybe anyone can help me?
Instead of declaring password a void **, declare it a void * and pass &password for the second-to-last parameter.
You probably don't need the SecKeychainItemRef for what you're trying to accomplish.
By the way, have you tried using Keychain Access to verify the items are getting into the keychain?

How to read Audio queue service bufer by byte?

I am recording sound from mic input using Audio queue service.
-(void)startRecording{
[self setupAudioFormat:&recordState.dataFormat];
recordState.currentPacket = 0;
OSStatus status;
status = AudioQueueNewInput(&recordState.dataFormat,
AudioInputCallback,
&recordState,
CFRunLoopGetCurrent(),
kCFRunLoopCommonModes,
0,
&recordState.queue);
if (status == 0)
{
// Prime recording buffers with empty data
for (int i = 0; i < NUM_BUFFERS; i++)
{
NSLog(#"buf in");
AudioQueueAllocateBuffer(recordState.queue, 16000, &recordState.buffers[i]);
AudioQueueEnqueueBuffer (recordState.queue, recordState.buffers[i], 0, NULL);
}
status = AudioFileCreateWithURL(fileURL,
kAudioFileAIFFType,
&recordState.dataFormat,
kAudioFileFlags_EraseFile,
&recordState.audioFile);
if (status == 0)
{
recordState.recording = true;
status = AudioQueueStart(recordState.queue, NULL);
if (status == 0)
{
NSLog(#"Recording");
}
}
}
if (status != 0)
{
//[self stopRecording];
NSLog(#"recording failed");
}
}
on callback:
void AudioInputCallback(void * inUserData,
AudioQueueRef inAQ,
AudioQueueBufferRef inBuffer,
const AudioTimeStamp * inStartTime,
UInt32 inNumberPacketDescriptions,
const AudioStreamPacketDescription * inPacketDescs)
{
RecordState * recordState = (RecordState*)inUserData;
if (!recordState->recording)
{
printf("Not recording, returning\n");
}
// if (inNumberPacketDescriptions == 0 && recordState->dataFormat.mBytesPerPacket != 0)
// {
// inNumberPacketDescriptions = inBuffer->mAudioDataByteSize / recordState->dataFormat.mBytesPerPacket;
// }
/*
int sampleCount = recordState->buffers[0]->mAudioDataBytesCapacity / sizeof (AUDIO_DATA_TYPE_FORMAT);
NSLog(#"sample count = %i",sampleCount);
AUDIO_DATA_TYPE_FORMAT *p = (AUDIO_DATA_TYPE_FORMAT*)recordState->buffers[0]->mAudioData;
for (int i = 0; i < sampleCount; i++) {
if (p[i] > 1000) {
NSLog(#"%hd",p[i]);
}
}*/
printf("Writing buffer %lld\n", recordState->currentPacket);
OSStatus status = AudioFileWritePackets(recordState->audioFile,
false,
inBuffer->mAudioDataByteSize,
inPacketDescs,
recordState->currentPacket,
&inNumberPacketDescriptions,
inBuffer->mAudioData);
if (status == 0)
{
recordState->buffers[0] = nil;
recordState->currentPacket += inNumberPacketDescriptions;
}
AudioQueueEnqueueBuffer(recordState->queue, inBuffer, 0, NULL);
}
Here i want to read recorded buffer. is it possible to get something like this:
short[] buffer = ?;//here should an audio buffer converted to some structure (short[] just for example)
then i would like to read every element of this structure:
for (int i = 0; i < sizeOfBuffer; i++) {
bufferVal = buffer[i];
}
In short how to handle buffer when recording ?
Thanks.