* Re: [PATCH] MSVC: Windows-native implementation for subset of Pthreads API
From: Andrzej K. Haczewski @ 2009-11-04 21:16 UTC (permalink / raw)
To: Nicolas Pitre; +Cc: git, Johannes Sixt
In-Reply-To: <alpine.LFD.2.00.0911041247250.10340@xanadu.home>
2009/11/4 Nicolas Pitre <nico@fluxnic.net>:
> On Wed, 4 Nov 2009, Andrzej K. Haczewski wrote:
>
>> + NO_STATIC_PTHREADS_INIT = YesPlease
>
> Let's not go that route please. If Windows can't get away without
> runtime initializations then let's use them on all platforms. There is
> no gain in exploding the code path combinations here wrt testing
> coverage.
>
I don't like that approach either, but I was frighten of Junio being
anal about static inits ;).
Let's make it clear: has anyone have any objections that I add
explicit initialization of mutexes and condition variables for POSIX
also?
>> +static THREAD_RET_TYPE threaded_find_deltas(void *arg)
>
> Why can't you just cast the function pointer in your pthread_create
> wrapper instead? No one cares about the returned value anyway.
Because of calling convention - I'd have to cast cdecl function as
stdcall function, which would change the function call clean up (in
cdecl caller is responsible for unwinding stack, stdcall callee; the
effect - double stack unwinding).
>> @@ -2327,6 +2354,8 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix)
>> #ifdef THREADED_DELTA_SEARCH
>> if (!delta_search_threads) /* --threads=0 means autodetect */
>> delta_search_threads = online_cpus();
>> +
>> + init_threaded_delta_search();
>
> What about doing this at the beginning of ll_find_deltas() instead?
> And similarly for cleanup_threaded_delta_search(): call it right before
> leaving ll_find_deltas(). This way thread issues would remain more
> localized. In fact I'd move the whole thing above in ll_find_deltas()
> as well (separately from this patch though).
Sounds sensible, but I'd wait for the NO_STATIC_PTHREADS_INIT verdict.
--
Andrzej
^ permalink raw reply
* Re: thoughts on setting core.logAllRefUpdates default true for bare repos
From: Matthieu Moy @ 2009-11-04 20:42 UTC (permalink / raw)
To: Junio C Hamano; +Cc: Johannes Schindelin, Sitaram Chamarty, git
In-Reply-To: <7v3a4ugjea.fsf@alter.siamese.dyndns.org>
Junio C Hamano <gitster@pobox.com> writes:
> Matthieu Moy <Matthieu.Moy@grenoble-inp.fr> writes:
>
>> I can't think of any, and I just tried launching two
>>
>> while true; do git pull; date > foo.txt ; git add .; git commit -m "xxx"; git push; done
>>
>> in parallel, with two different users pushing to a --bare --shared
>> repository, and it did work well. But I may very well have missed
>> something.
>>
>> (and actually, if it causes problem, it's an argument in favor of
>> defaulting to false when core.shared is true, not when core.bare).
>>
>> Unless I missed something, I think core.logAllRefUpdates should be
>> enabled for bare repos.
>
> Your experiment justifies "could be enabled safely" and saying "should be"
> based on that is a bit too strong and also premature.
Right, there were no cause/effect relationship between the first part
and the "should".
> As reflog is a local thing, and not exposed to outside world,
> enabling it alone would not help a lot to people who do not have
> such a direct access to the bare repository, which by definition is
> the majority because the reason why the repository is bare to begin
> with.
For sure, it's the majority. But it's not 100% cases either.
And in most cases, even if the user doesn't have access to the repo,
there exists a sysadmin somewhere who has. And the day a user will
send a mail "hey, I've messed up everything, I did a push -f and what
happened?", this sysadmin will appreciate to have a log somewhere.
And another use-case for the reflog is to find know reliable where a
piece of code is comming from. "git blame" tells you who the commiter
said he was, while the reflog says reliably who the push-er was.
So, clearly, the reflog on a bare repo is not usefull for daily use
like it is for non-bare repos (where, really, it's a killer
feature ;-) ). But it doesn't seem useless either, and it doesn't cost
much, so ...
--
Matthieu Moy
http://www-verimag.imag.fr/~moy/
^ permalink raw reply
* Re: [PATCH] MSVC: port pthread code to native Windows threads
From: Daniel Barkalow @ 2009-11-04 20:43 UTC (permalink / raw)
To: Andrzej K. Haczewski; +Cc: Johannes Sixt, git
In-Reply-To: <16cee31f0911040650s3eba1067mb66a48bb50c97c28@mail.gmail.com>
On Wed, 4 Nov 2009, Andrzej K. Haczewski wrote:
> 2009/11/4 Johannes Sixt <j.sixt@viscovery.net>:
> >
> > You are right. But #ifdef THREADED_DELTA_SEARCH is about a "generic"
> > property of the code and is already used elsewhere in the file, whereas
> > #ifdef WIN32 would be new and is is about platform differences.
> >
> > Anyway, we would have to see what Junio says about the new function calls,
> > because he's usually quite anal when it comes to added code vs. static
> > initialization. ;)
>
> I could do it with wrappers for pthread_mutex_lock and _unlock and
> lazy init there plus lazy init cond var in cond_wait and _signal, that
> way it could be done without any additional code in the first #ifdef.
> But I don't see any simple solution for working around
> deinitialization, that's why I'd leave non-static initialization. Let
> me put some touchups and resubmit for another round.
Is it actually necessary to deinitialize? Since the variables are static
and therefore can't leak, and would presumably not need to be
reinitialized differently if they were used again, I think they should be
able to just stay. If Windows is unhappy about processes still having
locks initialized at exit, I suppose we could go through and destroy all
our mutexes and conds at cleanup time. Pthreads does have the appropriate
functions, and it would be correct to use them, although unnecessary.
-Daniel
*This .sig left intentionally blank*
^ permalink raw reply
* Re: [PATCH 1/4] MSVC: Fix an "unresolved symbol" linker error on cygwin
From: Ramsay Jones @ 2009-11-04 20:20 UTC (permalink / raw)
To: Junio C Hamano; +Cc: Johannes Sixt, GIT Mailing-list, Marius Storm-Olsen
In-Reply-To: <7veiogt4g8.fsf@alter.siamese.dyndns.org>
Junio C Hamano wrote:
> How does Cygwin-ness of the build environment affect the end result when
> you build with MSVC?
Not at all. This is an MSVC/NO_MMAP combo problem. (The "problem" also exists
with the msvc build on msysGit[1])
> I am not a Windows person, so I am only guessing,
> but I suspect that the result does not pull any library nor crt0 from what
> people usually consider "Cygwin environment". It feels that the "default
> configuration of Cygwin" that insists on NO_MMAP is the guilty party here.
>
See patch #3.
> Shouldn't this be solved by teaching the Makefile about this new "Cygwin
> but using MSVC as compiler toolchain" combination?
Yes. Err... see patch #3 :-P
> [Footnote]
>
> *1* Notice "if" at the beginning of this sentence---I am not qualified to
> make a judgement without help from area experts here. Is it a sane thing
> to run Cygwin and still use MSVC as the compiler toolchain?
About as sane as running msysGit and still use MSVC as the compiler! :D
> Is it
> commonly done? I have no idea.
>
Nor me. I just tried it, and it works (after applying these patches!); for
exactly the same reason, and to the same extent, that it works on msysGit.
[Footnote]
*1* I admit to sometimes being a bit sloppy with naming (and maybe confused
also!). Now, IIUC, MinGW is basically gcc + binutils, MSYS is bash + some
unix tools and msysGit is MinGW + MSYS + some additional packages needed to
build and run git (eg perl). So, the "MinGW build" should really be called the
msysGit build ;-) (but the config section specifically picks out the MINGW string
from uname_S)
Also, the "msvc build on MinGW" should really be the "msvc build on msysGit".
Or something like that!
ATB,
Ramsay Jones
^ permalink raw reply
* Re: [PATCH 4/4] win32: Improve the conditional inclusion of WIN32 API code
From: Ramsay Jones @ 2009-11-04 19:40 UTC (permalink / raw)
To: Johannes Sixt; +Cc: Junio C Hamano, GIT Mailing-list, Marius Storm-Olsen
In-Reply-To: <4AEFDE9D.6060200@viscovery.net>
Johannes Sixt wrote:
> It may be that I understand something incorrectly; but then I blame the
> justification that you gave. In this case, it would be helpful to reword
> the commit message, and perhaps add some results from your experiments.
>
The discussion which lead to this patch, including the experiments, can be
found in the email thread starting here:
http://thread.gmane.org/gmane.comp.version-control.git/129403
(along with some other unrelated stuff; but it's not a long read :)
In the above thread, Marius suggested API_WIN32, but I switched it around, since
I thought it sounded better! I also thought about GIT_WIN32. Suggestions?
ATB,
Ramsay Jones
^ permalink raw reply
* Re: [PATCH 3/4] Makefile: keep MSVC and Cygwin configuration separate
From: Ramsay Jones @ 2009-11-04 19:29 UTC (permalink / raw)
To: Johannes Sixt; +Cc: Junio C Hamano, GIT Mailing-list, Marius Storm-Olsen
In-Reply-To: <4AEFDB6B.8010209@viscovery.net>
Johannes Sixt wrote:
>
> I like the direction of this change, but I think that you must use ':='
Yeah, I've always been a bit sloppy with recursive assignment versus simple
assignment when the value does not contain a variable reference ;-)
So yes, you are right...
> assignment, and I would put this right after the uname_* assignments at
> the beginning of the Makefile:
>
> uname_V := $(shell sh -c 'uname -v 2>/dev/null || echo not')
> +ifdef MSVC
> + uname_S := Windows
> + uname_O := Windows # avoid cygwin configuration
> +endif
OK with me. (but you are avoiding the MinGW configuration as well...)
ATB,
Ramsay Jones
^ permalink raw reply
* Re: [PATCH 0/4] Cygwin MSVC patches
From: Ramsay Jones @ 2009-11-04 19:03 UTC (permalink / raw)
To: Johannes Sixt; +Cc: Junio C Hamano, GIT Mailing-list, mstormo
In-Reply-To: <4AEFD6F9.5000305@viscovery.net>
Johannes Sixt wrote:
> Just to check I understand correctly: you are running "make MSVC=1" on
> cygwin, and then you are using the resulting binaries with the POSIX tools
> from cygwin.
Yes.
$ uname -a
CYGWIN_NT-5.1 toshiba 1.5.22(0.156/4/2) 2006-11-13 17:01 i686 Cygwin
$ pwd
/home/ramsay/git
$ make clean
[...output snipped...]
$ make MSVC=1
[...975 lines of output snipped; built OK...]
$ ./git --version
git version 1.6.5.4.g57e8c.MSVC
$
See original [PATCH 0/4] email for more...
ATB,
Ramsay Jones
^ permalink raw reply
* Re: [PATCH 1/4] MSVC: Fix an "unresolved symbol" linker error on cygwin
From: Ramsay Jones @ 2009-11-04 19:19 UTC (permalink / raw)
To: Johannes Sixt; +Cc: Junio C Hamano, GIT Mailing-list, Marius Storm-Olsen
In-Reply-To: <4AEFD9E2.6060004@viscovery.net>
Johannes Sixt wrote:
> Ramsay Jones schrieb:
>> When the NO_MMAP build variable is set, which is the case by
>> default on cygwin, the msvc linker complains:
>>
>> error LNK2001: unresolved external symbol _getpagesize
>
> Make up your mind: use the cygwin configuration or use the MSVC
> configuration. MSVC doesn't define NO_MMAP for a reason. Where is the problem?
Heh, well as I said elsewhere in this email, the "real problem" is that the
MSVC and cygwin configuration sections are not mutually exclusive and that
is fixed in patch #3. So, if you apply patch #3, this "problem" disappears.
However, ...
> I understand that you run into this error if you define NO_MMAP in your
> config.mak. I don't know whether we support NO_MMAP as a knob for to tweak
> the builds on all platforms. If this is the case (Junio?), then your
> justification must be updated.
AFAICT, the only build to not support NO_MMAP is MSVC (on cygwin *or* msysGit).
The solution was obvious and low impact, so why not remove this anomaly?
(It may even prove to be a useful capability ;-)
ATB,
Ramsay Jones
^ permalink raw reply
* Re: [PATCH 0/2] Set Makefile variables from configure
From: Ben Walton @ 2009-11-04 20:16 UTC (permalink / raw)
To: Junio C Hamano; +Cc: jrnieder, git
In-Reply-To: <7vy6mmf4hi.fsf@alter.siamese.dyndns.org>
[-- Attachment #1: Type: text/plain, Size: 1190 bytes --]
Excerpts from Junio C Hamano's message of Wed Nov 04 14:56:57 -0500 2009:
> What puzzled me was not "why is it not an error but just a warning?", which
> is what you just explained, but "why should we even care what value is
> being given to begin with?".
I'm sorry. I misunderstood then. I think that in most cases, setting
either 'yes' or 'no' is wrong, but I wanted to leave the door open for
it for the 1%. I thought that a warning message might be noticed and
cause someone to rethink.
> I am guessing from this description of 'oddball variables' that your
> answer to my question is yes. That is, configure.ac writers are
> strongly discouraged from using this new macro for variables that
> would usually get YesPlease/NoThanks kind of values.
Yes, that's correct. This new macro is for variables that are not a
simple toggle. It is also distinct from the mechanism used to specify
a path for perl, tcl/tk, etc, in that for those, we do want to error
out on no.
Thanks
-Ben
--
Ben Walton
Systems Programmer - CHASS
University of Toronto
C:416.407.5610 | W:416.978.4302
GPG Key Id: 8E89F6D2; Key Server: pgp.mit.edu
Contact me to arrange for a CAcert assurance meeting.
[-- Attachment #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 189 bytes --]
^ permalink raw reply
* Re: [PATCH 0/2] Set Makefile variables from configure
From: Jonathan Nieder @ 2009-11-04 20:16 UTC (permalink / raw)
To: Ben Walton; +Cc: Junio C Hamano, git
In-Reply-To: <1257363937-sup-5123@ntdws12.chass.utoronto.ca>
Ben Walton wrote:
> Excerpts from Junio C Hamano's message of Wed Nov 04 14:36:32 -0500 2009:
>
>> I am a bit puzzled about the "warning" logic. Is this because you expect
>> variables we typically give YesPlease/NoThanks as their values will not be
>> handled with this new PARSE_WITH_SET_MAKE_VAR() macro?
>
> No, this is because it's perfectly acceptable, in my opinion for a
> user to say:
>
> --with-pager=no
> or
> --with-editor=yes
More to the point, that’s what autoconf gives for "--without-pager" or
plain "--with-editor". It seems strange to silently use PAGER=no or
EDITOR=yes in that case.
Maybe the options should just be --pager=foo and --editor=bar, which
would be less misleading and avoid this problem. But this is not my
itch (I find it cleaner to use the Makefile directly), so I have no
strong opinion. Unfortunately, my autoconf-fu is too weak for a demo.
Jonathan
^ permalink raw reply
* Re: git subtree issues
From: Avery Pennarun @ 2009-11-04 19:57 UTC (permalink / raw)
To: Daniel Jacobs; +Cc: git
In-Reply-To: <bdccb6a00911031019y48f1d1aax9be7b49e3463595@mail.gmail.com>
On Tue, Nov 3, 2009 at 1:19 PM, Daniel Jacobs <daniel@sibblingz.com> wrote:
> Ok.. I ran the command as you suggested
> git pull -s subtree vw_extensions master
> remote: Counting objects: 5, done.
> remote: Compressing objects: 100% (3/3), done.
> remote: Total 3 (delta 2), reused 0 (delta 0)
> Unpacking objects: 100% (3/3), done.
> From git@github.com:sibblingz/vw_extensions
> * branch master -> FETCH_HEAD
> Already uptodate!
> Merge made by subtree.
>
> git diff --stat $(git merge-base HEAD^ FETCH_HEAD) FETCH_HEAD
> README | 2 +-
> 1 files changed, 1 insertions(+), 1 deletions(-)
> So, it knows there was a change. However, when I go and vim that README
> file, the change is not there. Maybe this gives you some more information.
This is extremely fishy. What if you re-run the pull without the "-s
subtree" at all? git must be trying to merge those changes in
*somewhere*...
> As an aside, I saw your git subtree tool, and it looks great, but I did not
> try to use it because I could not figure out how to install it. You might
> get a few more users if you include instructions for installation somewhere.
> :-)
Oops, good point. Somehow I forgot that. Fixed.
Thanks,
Avery
^ permalink raw reply
* Re: [PATCH 0/2] Set Makefile variables from configure
From: Junio C Hamano @ 2009-11-04 19:56 UTC (permalink / raw)
To: Ben Walton; +Cc: Junio C Hamano, jrnieder, git
In-Reply-To: <1257363937-sup-5123@ntdws12.chass.utoronto.ca>
Ben Walton <bwalton@artsci.utoronto.ca> writes:
> Excerpts from Junio C Hamano's message of Wed Nov 04 14:36:32 -0500 2009:
>
>> I am a bit puzzled about the "warning" logic. Is this because you expect
>> variables we typically give YesPlease/NoThanks as their values will not be
>> handled with this new PARSE_WITH_SET_MAKE_VAR() macro?
>
> No, this is because it's perfectly acceptable, in my opinion for a
> user to say:
>
> --with-pager=no
> or
> --with-editor=yes
>
> Neither of those are smart things to do, but they're not necessarily
> wrong, either. I'm open to bailing on error for these, but I thought
> leaving these as unvalidated, but with a warning, was more
> flexible...if say a user wanted to have a pager called 'no' or
> something.
What puzzled me was not "why is it not an error but just a warning?", which
is what you just explained, but "why should we even care what value is
being given to begin with?".
I am _not_ saying "I think it is more correct not to check the value at
all". I just wanted to understand in what situation it may be benefitial
to give this warning in the first place.
> For the variables that are accepting YesPlease/NoThanks, I think it's
> more suitable to use the standard autoconf header/function/library
> detection as it stands now. This macro is more for 'oddball'
> variables like DEFAULT_PAGER, DEFAULT_EDITOR, etc that aren't
> necessarily easily detectable. In some cases, even if it were
> detectable, the detection might not be right.
I am guessing from this description of 'oddball variables' that your
answer to my question is yes. That is, configure.ac writers are strongly
discouraged from using this new macro for variables that would usually get
YesPlease/NoThanks kind of values.
And then it makes sense to warn 'yes/no', as it is unlikely that the user
wants to set name (or path) of programs we allow to be tweaked to 'yes' or
'no'.
^ permalink raw reply
* [PATCH v2 04/13] Allow fetch to modify refs
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Daniel Barkalow, Sverre Rabbelier
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
From: Daniel Barkalow <barkalow@iabervon.org>
This allows the transport to use the null sha1 for a ref reported to
be present in the remote repository to indicate that a ref exists but
its actual value is presently unknown and will be set if the objects
are fetched.
Also adds documentation to the API to specify exactly what the methods
should do and how they should interpret arguments.
Signed-off-by: Daniel Barkalow <barkalow@iabervon.org>
Signed-off-by: Sverre Rabbelier <srabbelier@gmail.com>
---
Now only changes constness (changes to line 526-257 removed).
builtin-clone.c | 3 ++-
transport-helper.c | 4 ++--
transport.c | 13 +++++++------
transport.h | 41 +++++++++++++++++++++++++++++++++++++++--
4 files changed, 50 insertions(+), 11 deletions(-)
diff --git a/builtin-clone.c b/builtin-clone.c
index caf3025..5df8b0f 100644
--- a/builtin-clone.c
+++ b/builtin-clone.c
@@ -362,9 +362,10 @@ int cmd_clone(int argc, const char **argv, const char *prefix)
const char *repo_name, *repo, *work_tree, *git_dir;
char *path, *dir;
int dest_exists;
- const struct ref *refs, *remote_head, *mapped_refs;
+ const struct ref *refs, *remote_head;
const struct ref *remote_head_points_at;
const struct ref *our_head_points_at;
+ struct ref *mapped_refs;
struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
struct transport *transport = NULL;
diff --git a/transport-helper.c b/transport-helper.c
index e24fcbb..53d8f08 100644
--- a/transport-helper.c
+++ b/transport-helper.c
@@ -75,7 +75,7 @@ static int release_helper(struct transport *transport)
}
static int fetch_with_fetch(struct transport *transport,
- int nr_heads, const struct ref **to_fetch)
+ int nr_heads, struct ref **to_fetch)
{
struct child_process *helper = get_helper(transport);
FILE *file = xfdopen(helper->out, "r");
@@ -99,7 +99,7 @@ static int fetch_with_fetch(struct transport *transport,
}
static int fetch(struct transport *transport,
- int nr_heads, const struct ref **to_fetch)
+ int nr_heads, struct ref **to_fetch)
{
struct helper_data *data = transport->data;
int i, count;
diff --git a/transport.c b/transport.c
index 9daa686..5ae8db6 100644
--- a/transport.c
+++ b/transport.c
@@ -204,7 +204,7 @@ static struct ref *get_refs_via_rsync(struct transport *transport, int for_push)
}
static int fetch_objs_via_rsync(struct transport *transport,
- int nr_objs, const struct ref **to_fetch)
+ int nr_objs, struct ref **to_fetch)
{
struct strbuf buf = STRBUF_INIT;
struct child_process rsync;
@@ -408,7 +408,7 @@ static struct ref *get_refs_from_bundle(struct transport *transport, int for_pus
}
static int fetch_refs_from_bundle(struct transport *transport,
- int nr_heads, const struct ref **to_fetch)
+ int nr_heads, struct ref **to_fetch)
{
struct bundle_transport_data *data = transport->data;
return unbundle(&data->header, data->fd);
@@ -486,7 +486,7 @@ static struct ref *get_refs_via_connect(struct transport *transport, int for_pus
}
static int fetch_refs_via_pack(struct transport *transport,
- int nr_heads, const struct ref **to_fetch)
+ int nr_heads, struct ref **to_fetch)
{
struct git_transport_data *data = transport->data;
char **heads = xmalloc(nr_heads * sizeof(*heads));
@@ -926,16 +926,17 @@ const struct ref *transport_get_remote_refs(struct transport *transport)
return transport->remote_refs;
}
-int transport_fetch_refs(struct transport *transport, const struct ref *refs)
+int transport_fetch_refs(struct transport *transport, struct ref *refs)
{
int rc;
int nr_heads = 0, nr_alloc = 0, nr_refs = 0;
- const struct ref **heads = NULL;
- const struct ref *rm;
+ struct ref **heads = NULL;
+ struct ref *rm;
for (rm = refs; rm; rm = rm->next) {
nr_refs++;
if (rm->peer_ref &&
+ !is_null_sha1(rm->old_sha1) &&
!hashcmp(rm->peer_ref->old_sha1, rm->old_sha1))
continue;
ALLOC_GROW(heads, nr_heads + 1, nr_alloc);
diff --git a/transport.h b/transport.h
index c14da6f..503db11 100644
--- a/transport.h
+++ b/transport.h
@@ -18,11 +18,48 @@ struct transport {
int (*set_option)(struct transport *connection, const char *name,
const char *value);
+ /**
+ * Returns a list of the remote side's refs. In order to allow
+ * the transport to try to share connections, for_push is a
+ * hint as to whether the ultimate operation is a push or a fetch.
+ *
+ * If the transport is able to determine the remote hash for
+ * the ref without a huge amount of effort, it should store it
+ * in the ref's old_sha1 field; otherwise it should be all 0.
+ **/
struct ref *(*get_refs_list)(struct transport *transport, int for_push);
- int (*fetch)(struct transport *transport, int refs_nr, const struct ref **refs);
+
+ /**
+ * Fetch the objects for the given refs. Note that this gets
+ * an array, and should ignore the list structure.
+ *
+ * If the transport did not get hashes for refs in
+ * get_refs_list(), it should set the old_sha1 fields in the
+ * provided refs now.
+ **/
+ int (*fetch)(struct transport *transport, int refs_nr, struct ref **refs);
+
+ /**
+ * Push the objects and refs. Send the necessary objects, and
+ * then, for any refs where peer_ref is set and
+ * peer_ref->new_sha1 is different from old_sha1, tell the
+ * remote side to update each ref in the list from old_sha1 to
+ * peer_ref->new_sha1.
+ *
+ * Where possible, set the status for each ref appropriately.
+ *
+ * The transport must modify new_sha1 in the ref to the new
+ * value if the remote accepted the change. Note that this
+ * could be a different value from peer_ref->new_sha1 if the
+ * process involved generating new commits.
+ **/
int (*push_refs)(struct transport *transport, struct ref *refs, int flags);
int (*push)(struct transport *connection, int refspec_nr, const char **refspec, int flags);
+ /** get_refs_list(), fetch(), and push_refs() can keep
+ * resources (such as a connection) reserved for futher
+ * use. disconnect() releases these resources.
+ **/
int (*disconnect)(struct transport *connection);
char *pack_lockfile;
signed verbose : 2;
@@ -74,7 +111,7 @@ int transport_push(struct transport *connection,
const struct ref *transport_get_remote_refs(struct transport *transport);
-int transport_fetch_refs(struct transport *transport, const struct ref *refs);
+int transport_fetch_refs(struct transport *transport, struct ref *refs);
void transport_unlock_pack(struct transport *transport);
int transport_disconnect(struct transport *transport);
char *transport_anonymize_url(const char *url);
--
1.6.5.2.295.g0d105
^ permalink raw reply related
* [PATCH v2 02/13] Allow programs to not depend on remotes having urls
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Daniel Barkalow, Sverre Rabbelier
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
From: Daniel Barkalow <barkalow@iabervon.org>
For fetch and ls-remote, which use the first url of a remote, have
transport_get() determine this by passing a remote and passing NULL
for the url. For push, which uses every url of a remote, use each url
in turn if there are any, and use NULL if there are none.
This will allow the transport code to do something different if the
location is not specified with a url.
Also, have the message for a fetch say "foreign" if there is no url.
Signed-off-by: Daniel Barkalow <barkalow@iabervon.org>
Signed-off-by: Sverre Rabbelier <srabbelier@gmail.com>
---
Unchanged.
builtin-fetch.c | 7 +++-
builtin-ls-remote.c | 4 +-
builtin-push.c | 68 +++++++++++++++++++++++++++++++-------------------
transport.c | 3 ++
4 files changed, 52 insertions(+), 30 deletions(-)
diff --git a/builtin-fetch.c b/builtin-fetch.c
index a35a6f8..013a6ba 100644
--- a/builtin-fetch.c
+++ b/builtin-fetch.c
@@ -309,7 +309,10 @@ static int store_updated_refs(const char *raw_url, const char *remote_name,
if (!fp)
return error("cannot open %s: %s\n", filename, strerror(errno));
- url = transport_anonymize_url(raw_url);
+ if (raw_url)
+ url = transport_anonymize_url(raw_url);
+ else
+ url = xstrdup("foreign");
for (rm = ref_map; rm; rm = rm->next) {
struct ref *ref = NULL;
@@ -704,7 +707,7 @@ int cmd_fetch(int argc, const char **argv, const char *prefix)
if (!remote)
die("Where do you want to fetch from today?");
- transport = transport_get(remote, remote->url[0]);
+ transport = transport_get(remote, NULL);
if (verbosity >= 2)
transport->verbose = 1;
if (verbosity < 0)
diff --git a/builtin-ls-remote.c b/builtin-ls-remote.c
index 78a88f7..4c6fc58 100644
--- a/builtin-ls-remote.c
+++ b/builtin-ls-remote.c
@@ -87,9 +87,9 @@ int cmd_ls_remote(int argc, const char **argv, const char *prefix)
}
}
remote = nongit ? NULL : remote_get(dest);
- if (remote && !remote->url_nr)
+ if (!nongit && !remote)
die("remote %s has no configured URL", dest);
- transport = transport_get(remote, remote ? remote->url[0] : dest);
+ transport = transport_get(remote, remote ? NULL : dest);
if (uploadpack != NULL)
transport_set_option(transport, TRANS_OPT_UPLOADPACK, uploadpack);
diff --git a/builtin-push.c b/builtin-push.c
index 8631c06..88dd9f5 100644
--- a/builtin-push.c
+++ b/builtin-push.c
@@ -88,6 +88,36 @@ static void setup_default_push_refspecs(void)
}
}
+static int push_with_options(struct transport *transport, int flags)
+{
+ int err;
+ int nonfastforward;
+ if (receivepack)
+ transport_set_option(transport,
+ TRANS_OPT_RECEIVEPACK, receivepack);
+ if (thin)
+ transport_set_option(transport, TRANS_OPT_THIN, "yes");
+
+ if (flags & TRANSPORT_PUSH_VERBOSE)
+ fprintf(stderr, "Pushing to %s\n", transport->url);
+ err = transport_push(transport, refspec_nr, refspec, flags,
+ &nonfastforward);
+ err |= transport_disconnect(transport);
+
+ if (!err)
+ return 0;
+
+ error("failed to push some refs to '%s'", transport->url);
+
+ if (nonfastforward && advice_push_nonfastforward) {
+ printf("To prevent you from losing history, non-fast-forward updates were rejected\n"
+ "Merge the remote changes before pushing again. See the 'non-fast forward'\n"
+ "section of 'git push --help' for details.\n");
+ }
+
+ return 1;
+}
+
static int do_push(const char *repo, int flags)
{
int i, errs;
@@ -136,33 +166,19 @@ static int do_push(const char *repo, int flags)
url = remote->url;
url_nr = remote->url_nr;
}
- for (i = 0; i < url_nr; i++) {
- struct transport *transport =
- transport_get(remote, url[i]);
- int err;
- int nonfastforward;
- if (receivepack)
- transport_set_option(transport,
- TRANS_OPT_RECEIVEPACK, receivepack);
- if (thin)
- transport_set_option(transport, TRANS_OPT_THIN, "yes");
-
- if (flags & TRANSPORT_PUSH_VERBOSE)
- fprintf(stderr, "Pushing to %s\n", url[i]);
- err = transport_push(transport, refspec_nr, refspec, flags,
- &nonfastforward);
- err |= transport_disconnect(transport);
-
- if (!err)
- continue;
-
- error("failed to push some refs to '%s'", url[i]);
- if (nonfastforward && advice_push_nonfastforward) {
- printf("To prevent you from losing history, non-fast-forward updates were rejected\n"
- "Merge the remote changes before pushing again. See the 'non-fast forward'\n"
- "section of 'git push --help' for details.\n");
+ if (url_nr) {
+ for (i = 0; i < url_nr; i++) {
+ struct transport *transport =
+ transport_get(remote, url[i]);
+ if (push_with_options(transport, flags))
+ errs++;
}
- errs++;
+ } else {
+ struct transport *transport =
+ transport_get(remote, NULL);
+
+ if (push_with_options(transport, flags))
+ errs++;
}
return !!errs;
}
diff --git a/transport.c b/transport.c
index 644a30a..9daa686 100644
--- a/transport.c
+++ b/transport.c
@@ -813,6 +813,9 @@ struct transport *transport_get(struct remote *remote, const char *url)
struct transport *ret = xcalloc(1, sizeof(*ret));
ret->remote = remote;
+
+ if (!url && remote && remote->url)
+ url = remote->url[0];
ret->url = url;
if (!prefixcmp(url, "rsync:")) {
--
1.6.5.2.295.g0d105
^ permalink raw reply related
* [PATCH v2 01/13] Fix memory leak in helper method for disconnect
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Daniel Barkalow
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
From: Daniel Barkalow <barkalow@iabervon.org>
Since some cases may need to disconnect from the helper and reconnect,
wrap the function that just disconnects in a function that also frees
transport->data.
Signed-off-by: Daniel Barkalow <barkalow@iabervon.org>
---
Moved to the beginning of the series as it is most important.
transport-helper.c | 9 ++++++++-
1 files changed, 8 insertions(+), 1 deletions(-)
diff --git a/transport-helper.c b/transport-helper.c
index f57e84c..e24fcbb 100644
--- a/transport-helper.c
+++ b/transport-helper.c
@@ -67,6 +67,13 @@ static int disconnect_helper(struct transport *transport)
return 0;
}
+static int release_helper(struct transport *transport)
+{
+ disconnect_helper(transport);
+ free(transport->data);
+ return 0;
+}
+
static int fetch_with_fetch(struct transport *transport,
int nr_heads, const struct ref **to_fetch)
{
@@ -163,6 +170,6 @@ int transport_helper_init(struct transport *transport, const char *name)
transport->data = data;
transport->get_refs_list = get_refs_list;
transport->fetch = fetch;
- transport->disconnect = disconnect_helper;
+ transport->disconnect = release_helper;
return 0;
}
--
1.6.5.2.295.g0d105
^ permalink raw reply related
* Re: thoughts on setting core.logAllRefUpdates default true for bare repos
From: Junio C Hamano @ 2009-11-04 19:49 UTC (permalink / raw)
To: Matthieu Moy; +Cc: Johannes Schindelin, Sitaram Chamarty, git
In-Reply-To: <vpqzl729j72.fsf@bauges.imag.fr>
Matthieu Moy <Matthieu.Moy@grenoble-inp.fr> writes:
> I can't think of any, and I just tried launching two
>
> while true; do git pull; date > foo.txt ; git add .; git commit -m "xxx"; git push; done
>
> in parallel, with two different users pushing to a --bare --shared
> repository, and it did work well. But I may very well have missed
> something.
>
> (and actually, if it causes problem, it's an argument in favor of
> defaulting to false when core.shared is true, not when core.bare).
>
> Unless I missed something, I think core.logAllRefUpdates should be
> enabled for bare repos.
Your experiment justifies "could be enabled safely" and saying "should be"
based on that is a bit too strong and also premature.
The single most common reason why a bare repository is bare is because
nobody regularly logs in to the machine that hosts it and goes there to
access its contents. As reflog is a local thing, and not exposed to
outside world, enabling it alone would not help a lot to people who do not
have such a direct access to the bare repository, which by definition is
the majority because the reason why the repository is bare to begin with.
Once we add ways to expose information kept in reflog of a bare repository
more effectively and conveniently, the argument could become "should be
enabled now it would be very useful to have one".
I mentioned a possible option to show reflog entry annotations in gitweb.
That was an example of such an addition of "a way to expose".
It also is plausible to teach git-daemon a remote "log" request; similar
to "git fetch" running "upload-pack" on the other end in the bare
repository, a "git log --remote" command may run "upload-log" on the other
end and this service may allow passing the "-g" option when it does so.
That would be another addition of "a way to expose".
^ permalink raw reply
* [PATCH v2 08/13] Write local refs written by the "import" helper command only once
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Sverre Rabbelier
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
At clone time the "import" helper command has already written a
packfile with all refs, so write_remote_refs will create a duplicate
entry for each ref returned by wanted_peer_refs. Prevent this
duplication by setting fetched_refs_written in the transport when
executing the "import" helper command and only adding the extra refs
if it is not set.
Signed-off-by: Sverre Rabbelier <srabbelier@gmail.com>
---
I am not 100% sure this is the proper fix, but I do know that
without this I get a .git/packed-refs file that has duplicate
entries in it.
builtin-clone.c | 5 ++++-
transport-helper.c | 3 +++
transport.h | 2 ++
3 files changed, 9 insertions(+), 1 deletions(-)
diff --git a/builtin-clone.c b/builtin-clone.c
index 5df8b0f..e44347e 100644
--- a/builtin-clone.c
+++ b/builtin-clone.c
@@ -542,7 +542,10 @@ int cmd_clone(int argc, const char **argv, const char *prefix)
if (refs) {
clear_extra_refs();
- write_remote_refs(mapped_refs);
+ if(transport->fetched_refs_written)
+ pack_refs(PACK_REFS_ALL);
+ else
+ write_remote_refs(mapped_refs);
remote_head = find_ref_by_name(refs, "HEAD");
remote_head_points_at =
diff --git a/transport-helper.c b/transport-helper.c
index 82caaae..148496c 100644
--- a/transport-helper.c
+++ b/transport-helper.c
@@ -165,7 +165,10 @@ static int fetch(struct transport *transport,
return fetch_with_fetch(transport, nr_heads, to_fetch);
if (data->import)
+ {
+ transport->fetched_refs_written = 1;
return fetch_with_import(transport, nr_heads, to_fetch);
+ }
return -1;
}
diff --git a/transport.h b/transport.h
index 503db11..7458b9e 100644
--- a/transport.h
+++ b/transport.h
@@ -65,6 +65,8 @@ struct transport {
signed verbose : 2;
/* Force progress even if the output is not a tty */
unsigned progress : 1;
+ /* Refs fetched by transport_get_remote_refs are already written */
+ unsigned fetched_refs_written : 1;
};
#define TRANSPORT_PUSH_ALL 1
--
1.6.5.2.295.g0d105
^ permalink raw reply related
* [PATCH v2 11/13] Allow helpers to request the path to the .git directory
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Sverre Rabbelier
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
The 'gitdir' capability is reported by the remote helper if it
requires the location of the .git directory. The location of the .git
directory can then be used by the helper to store status files even
when the current directory is not a git repository (such as is the
case when cloning).
The location of the .git dir is specified as an absolute path.
Signed-off-by: Sverre Rabbelier <srabbelier@gmail.com>
---
Daniel, is this a good idea, or should we perhaps tell the
helper the location of the git repository otherwise?
transport-helper.c | 6 ++++++
1 files changed, 6 insertions(+), 0 deletions(-)
diff --git a/transport-helper.c b/transport-helper.c
index a80d803..4f95e7b 100644
--- a/transport-helper.c
+++ b/transport-helper.c
@@ -51,6 +51,12 @@ static struct child_process *get_helper(struct transport *transport)
data->fetch = 1;
if (!strcmp(buf.buf, "import"))
data->import = 1;
+ if (!strcmp(buf.buf, "gitdir")) {
+ struct strbuf gitdir = STRBUF_INIT;
+ strbuf_addf(&gitdir, "gitdir %s\n", get_git_dir());
+ write_in_full(helper->in, gitdir.buf, gitdir.len);
+ strbuf_reset(&gitdir);
+ }
}
return data->helper;
}
--
1.6.5.2.295.g0d105
^ permalink raw reply related
* [PATCH v2 13/13] Add Python support library for remote helpers
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Sverre Rabbelier, David Aguilar, Johan Herland
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
This patch introduces parts of a Python package called
"git_remote_helpers" containing the building blocks for
python helper.
The actual remote helpers itself are NOT part of this patch.
The patch includes the necessary Makefile additions to build and install
the git_remote_cvs Python package along with the rest of Git.
This patch is based on Johan Herland's git_remote_cvs patch and
has been improved by the following contributions:
- David Aguilar: Lots of Python coding style fixes
- David Aguilar: DESTDIR support in Makefile
Cc: David Aguilar <davvid@gmail.com>
Cc: Johan Herland <johan@herland.net>
Signed-off-by: Sverre Rabbelier <srabbelier@gmail.com>
---
Ejected all cvs specific parts (I grepped :P).
Makefile | 38 ++
git_remote_helpers/.gitignore | 2 +
git_remote_helpers/Makefile | 35 ++
git_remote_helpers/__init__.py | 16 +
git_remote_helpers/git/git.py | 678 ++++++++++++++++++++++++++++++++++++
git_remote_helpers/setup.py | 17 +
git_remote_helpers/util.py | 194 ++++++++++
t/test-lib.sh | 9 +
8 files changed, 989 insertions(+), 0 deletions(-)
create mode 100644 git_remote_helpers/.gitignore
create mode 100644 git_remote_helpers/Makefile
create mode 100644 git_remote_helpers/__init__.py
create mode 100644 git_remote_helpers/git/__init__.py
create mode 100644 git_remote_helpers/git/git.py
create mode 100644 git_remote_helpers/setup.py
create mode 100644 git_remote_helpers/util.py
diff --git a/Makefile b/Makefile
index 6d1593f..701439f 100644
--- a/Makefile
+++ b/Makefile
@@ -1406,6 +1406,9 @@ endif
ifndef NO_PERL
$(QUIET_SUBDIR0)perl $(QUIET_SUBDIR1) PERL_PATH='$(PERL_PATH_SQ)' prefix='$(prefix_SQ)' all
endif
+ifndef NO_PYTHON
+ $(QUIET_SUBDIR0)git_remote_helpers $(QUIET_SUBDIR1) PYTHON_PATH='$(PYTHON_PATH_SQ)' prefix='$(prefix_SQ)' all
+endif
$(QUIET_SUBDIR0)templates $(QUIET_SUBDIR1)
please_set_SHELL_PATH_to_a_more_modern_shell:
@@ -1524,6 +1527,35 @@ $(patsubst %.perl,%,$(SCRIPT_PERL)) git-instaweb: % : unimplemented.sh
mv $@+ $@
endif # NO_PERL
+ifndef NO_PYTHON
+$(patsubst %.py,%,$(SCRIPT_PYTHON)): GIT-CFLAGS
+$(patsubst %.py,%,$(SCRIPT_PYTHON)): % : %.py
+ $(QUIET_GEN)$(RM) $@ $@+ && \
+ INSTLIBDIR=`MAKEFLAGS= $(MAKE) -C git_remote_helpers -s \
+ --no-print-directory prefix='$(prefix_SQ)' DESTDIR='$(DESTDIR_SQ)' \
+ instlibdir` && \
+ sed -e '1{' \
+ -e ' s|#!.*python|#!$(PYTHON_PATH_SQ)|' \
+ -e '}' \
+ -e 's|^import sys.*|&; \\\
+ import os; \\\
+ sys.path[0] = os.environ.has_key("GITPYTHONLIB") and \\\
+ os.environ["GITPYTHONLIB"] or \\\
+ "@@INSTLIBDIR@@"|' \
+ -e 's|@@INSTLIBDIR@@|'"$$INSTLIBDIR"'|g' \
+ $@.py >$@+ && \
+ chmod +x $@+ && \
+ mv $@+ $@
+else # NO_PYTHON
+$(patsubst %.py,%,$(SCRIPT_PYTHON)): % : unimplemented.sh
+ $(QUIET_GEN)$(RM) $@ $@+ && \
+ sed -e '1s|#!.*/sh|#!$(SHELL_PATH_SQ)|' \
+ -e 's|@@REASON@@|NO_PYTHON=$(NO_PYTHON)|g' \
+ unimplemented.sh >$@+ && \
+ chmod +x $@+ && \
+ mv $@+ $@
+endif # NO_PYTHON
+
configure: configure.ac
$(QUIET_GEN)$(RM) $@ $<+ && \
sed -e 's/@@GIT_VERSION@@/$(GIT_VERSION)/g' \
@@ -1748,6 +1780,9 @@ install: all
ifndef NO_PERL
$(MAKE) -C perl prefix='$(prefix_SQ)' DESTDIR='$(DESTDIR_SQ)' install
endif
+ifndef NO_PYTHON
+ $(MAKE) -C git_remote_helpers prefix='$(prefix_SQ)' DESTDIR='$(DESTDIR_SQ)' install
+endif
ifndef NO_TCLTK
$(MAKE) -C gitk-git install
$(MAKE) -C git-gui gitexecdir='$(gitexec_instdir_SQ)' install
@@ -1862,6 +1897,9 @@ ifndef NO_PERL
$(RM) gitweb/gitweb.cgi
$(MAKE) -C perl clean
endif
+ifndef NO_PYTHON
+ $(MAKE) -C git_remote_helpers clean
+endif
$(MAKE) -C templates/ clean
$(MAKE) -C t/ clean
ifndef NO_TCLTK
diff --git a/git_remote_helpers/.gitignore b/git_remote_helpers/.gitignore
new file mode 100644
index 0000000..2247d5f
--- /dev/null
+++ b/git_remote_helpers/.gitignore
@@ -0,0 +1,2 @@
+/build
+/dist
diff --git a/git_remote_helpers/Makefile b/git_remote_helpers/Makefile
new file mode 100644
index 0000000..c62dfd0
--- /dev/null
+++ b/git_remote_helpers/Makefile
@@ -0,0 +1,35 @@
+#
+# Makefile for the git_remote_helpers python support modules
+#
+pysetupfile:=setup.py
+
+# Shell quote (do not use $(call) to accommodate ancient setups);
+DESTDIR_SQ = $(subst ','\'',$(DESTDIR))
+
+ifndef PYTHON_PATH
+ PYTHON_PATH = /usr/bin/python
+endif
+ifndef prefix
+ prefix = $(HOME)
+endif
+ifndef V
+ QUIET = @
+ QUIETSETUP = --quiet
+endif
+
+PYLIBDIR=$(shell $(PYTHON_PATH) -c \
+ "import sys; \
+ print 'lib/python%i.%i/site-packages' % sys.version_info[:2]")
+
+all: $(pysetupfile)
+ $(QUIET)$(PYTHON_PATH) $(pysetupfile) $(QUIETSETUP) build
+
+install: $(pysetupfile)
+ $(PYTHON_PATH) $(pysetupfile) install --prefix $(DESTDIR_SQ)$(prefix)
+
+instlibdir: $(pysetupfile)
+ @echo "$(DESTDIR_SQ)$(prefix)/$(PYLIBDIR)"
+
+clean:
+ $(QUIET)$(PYTHON_PATH) $(pysetupfile) $(QUIETSETUP) clean -a
+ $(RM) *.pyo *.pyc
diff --git a/git_remote_helpers/__init__.py b/git_remote_helpers/__init__.py
new file mode 100644
index 0000000..00f69cb
--- /dev/null
+++ b/git_remote_helpers/__init__.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python
+
+"""Support library package for git remote helpers.
+
+Git remote helpers are helper commands that interfaces with a non-git
+repository to provide automatic import of non-git history into a Git
+repository.
+
+This package provides the support library needed by these helpers..
+The following modules are included:
+
+- git.git - Interaction with Git repositories
+
+- util - General utility functionality use by the other modules in
+ this package, and also used directly by the helpers.
+"""
diff --git a/git_remote_helpers/git/__init__.py b/git_remote_helpers/git/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/git_remote_helpers/git/git.py b/git_remote_helpers/git/git.py
new file mode 100644
index 0000000..a383e6c
--- /dev/null
+++ b/git_remote_helpers/git/git.py
@@ -0,0 +1,678 @@
+#!/usr/bin/env python
+
+"""Functionality for interacting with Git repositories.
+
+This module provides classes for interfacing with a Git repository.
+"""
+
+import os
+import re
+import time
+from binascii import hexlify
+from cStringIO import StringIO
+import unittest
+
+from git_remote_helpers.util import debug, error, die, start_command, run_command
+
+
+def get_git_dir ():
+ """Return the path to the GIT_DIR for this repo."""
+ args = ("git", "rev-parse", "--git-dir")
+ exit_code, output, errors = run_command(args)
+ if exit_code:
+ die("Failed to retrieve git dir")
+ assert not errors
+ return output.strip()
+
+
+def parse_git_config ():
+ """Return a dict containing the parsed version of 'git config -l'."""
+ exit_code, output, errors = run_command(("git", "config", "-z", "-l"))
+ if exit_code:
+ die("Failed to retrieve git configuration")
+ assert not errors
+ return dict([e.split('\n', 1) for e in output.split("\0") if e])
+
+
+def git_config_bool (value):
+ """Convert the given git config string value to True or False.
+
+ Raise ValueError if the given string was not recognized as a
+ boolean value.
+
+ """
+ norm_value = str(value).strip().lower()
+ if norm_value in ("true", "1", "yes", "on", ""):
+ return True
+ if norm_value in ("false", "0", "no", "off", "none"):
+ return False
+ raise ValueError("Failed to parse '%s' into a boolean value" % (value))
+
+
+def valid_git_ref (ref_name):
+ """Return True iff the given ref name is a valid git ref name."""
+ # The following is a reimplementation of the git check-ref-format
+ # command. The rules were derived from the git check-ref-format(1)
+ # manual page. This code should be replaced by a call to
+ # check_ref_format() in the git library, when such is available.
+ if ref_name.endswith('/') or \
+ ref_name.startswith('.') or \
+ ref_name.count('/.') or \
+ ref_name.count('..') or \
+ ref_name.endswith('.lock'):
+ return False
+ for c in ref_name:
+ if ord(c) < 0x20 or ord(c) == 0x7f or c in " ~^:?*[":
+ return False
+ return True
+
+
+class GitObjectFetcher(object):
+
+ """Provide parsed access to 'git cat-file --batch'.
+
+ This provides a read-only interface to the Git object database.
+
+ """
+
+ def __init__ (self):
+ """Initiate a 'git cat-file --batch' session."""
+ self.queue = [] # List of object names to be submitted
+ self.in_transit = None # Object name currently in transit
+
+ # 'git cat-file --batch' produces binary output which is likely
+ # to be corrupted by the default "rU"-mode pipe opened by
+ # start_command. (Mode == "rU" does universal new-line
+ # conversion, which mangles carriage returns.) Therefore, we
+ # open an explicitly binary-safe pipe for transferring the
+ # output from 'git cat-file --batch'.
+ pipe_r_fd, pipe_w_fd = os.pipe()
+ pipe_r = os.fdopen(pipe_r_fd, "rb")
+ pipe_w = os.fdopen(pipe_w_fd, "wb")
+ self.proc = start_command(("git", "cat-file", "--batch"),
+ stdout = pipe_w)
+ self.f = pipe_r
+
+ def __del__ (self):
+ """Verify completed communication with 'git cat-file --batch'."""
+ assert not self.queue
+ assert self.in_transit is None
+ self.proc.stdin.close()
+ assert self.proc.wait() == 0 # Zero exit code
+ assert self.f.read() == "" # No remaining output
+
+ def _submit_next_object (self):
+ """Submit queue items to the 'git cat-file --batch' process.
+
+ If there are items in the queue, and there is currently no item
+ currently in 'transit', then pop the first item off the queue,
+ and submit it.
+
+ """
+ if self.queue and self.in_transit is None:
+ self.in_transit = self.queue.pop(0)
+ print >> self.proc.stdin, self.in_transit[0]
+
+ def push (self, obj, callback):
+ """Push the given object name onto the queue.
+
+ The given callback function will at some point in the future
+ be called exactly once with the following arguments:
+ - self - this GitObjectFetcher instance
+ - obj - the object name provided to push()
+ - sha1 - the SHA1 of the object, if 'None' obj is missing
+ - t - the type of the object (tag/commit/tree/blob)
+ - size - the size of the object in bytes
+ - data - the object contents
+
+ """
+ self.queue.append((obj, callback))
+ self._submit_next_object() # (Re)start queue processing
+
+ def process_next_entry (self):
+ """Read the next entry off the queue and invoke callback."""
+ obj, cb = self.in_transit
+ self.in_transit = None
+ header = self.f.readline()
+ if header == "%s missing\n" % (obj):
+ cb(self, obj, None, None, None, None)
+ return
+ sha1, t, size = header.split(" ")
+ assert len(sha1) == 40
+ assert t in ("tag", "commit", "tree", "blob")
+ assert size.endswith("\n")
+ size = int(size.strip())
+ data = self.f.read(size)
+ assert self.f.read(1) == "\n"
+ cb(self, obj, sha1, t, size, data)
+ self._submit_next_object()
+
+ def process (self):
+ """Process the current queue until empty."""
+ while self.in_transit is not None:
+ self.process_next_entry()
+
+ # High-level convenience methods:
+
+ def get_sha1 (self, objspec):
+ """Return the SHA1 of the object specified by 'objspec'.
+
+ Return None if 'objspec' does not specify an existing object.
+
+ """
+ class _ObjHandler(object):
+ """Helper class for getting the returned SHA1."""
+ def __init__ (self, parser):
+ self.parser = parser
+ self.sha1 = None
+
+ def __call__ (self, parser, obj, sha1, t, size, data):
+ # FIXME: Many unused arguments. Could this be cheaper?
+ assert parser == self.parser
+ self.sha1 = sha1
+
+ handler = _ObjHandler(self)
+ self.push(objspec, handler)
+ self.process()
+ return handler.sha1
+
+ def open_obj (self, objspec):
+ """Return a file object wrapping the contents of a named object.
+
+ The caller is responsible for calling .close() on the returned
+ file object.
+
+ Raise KeyError if 'objspec' does not exist in the repo.
+
+ """
+ class _ObjHandler(object):
+ """Helper class for parsing the returned git object."""
+ def __init__ (self, parser):
+ """Set up helper."""
+ self.parser = parser
+ self.contents = StringIO()
+ self.err = None
+
+ def __call__ (self, parser, obj, sha1, t, size, data):
+ """Git object callback (see GitObjectFetcher documentation)."""
+ assert parser == self.parser
+ if not sha1: # Missing object
+ self.err = "Missing object '%s'" % obj
+ else:
+ assert size == len(data)
+ self.contents.write(data)
+
+ handler = _ObjHandler(self)
+ self.push(objspec, handler)
+ self.process()
+ if handler.err:
+ raise KeyError(handler.err)
+ handler.contents.seek(0)
+ return handler.contents
+
+ def walk_tree (self, tree_objspec, callback, prefix = ""):
+ """Recursively walk the given Git tree object.
+
+ Recursively walk all subtrees of the given tree object, and
+ invoke the given callback passing three arguments:
+ (path, mode, data) with the path, permission bits, and contents
+ of all the blobs found in the entire tree structure.
+
+ """
+ class _ObjHandler(object):
+ """Helper class for walking a git tree structure."""
+ def __init__ (self, parser, cb, path, mode = None):
+ """Set up helper."""
+ self.parser = parser
+ self.cb = cb
+ self.path = path
+ self.mode = mode
+ self.err = None
+
+ def parse_tree (self, treedata):
+ """Parse tree object data, yield tree entries.
+
+ Each tree entry is a 3-tuple (mode, sha1, path)
+
+ self.path is prepended to all paths yielded
+ from this method.
+
+ """
+ while treedata:
+ mode = int(treedata[:6], 10)
+ # Turn 100xxx into xxx
+ if mode > 100000:
+ mode -= 100000
+ assert treedata[6] == " "
+ i = treedata.find("\0", 7)
+ assert i > 0
+ path = treedata[7:i]
+ sha1 = hexlify(treedata[i + 1: i + 21])
+ yield (mode, sha1, self.path + path)
+ treedata = treedata[i + 21:]
+
+ def __call__ (self, parser, obj, sha1, t, size, data):
+ """Git object callback (see GitObjectFetcher documentation)."""
+ assert parser == self.parser
+ if not sha1: # Missing object
+ self.err = "Missing object '%s'" % (obj)
+ return
+ assert size == len(data)
+ if t == "tree":
+ if self.path:
+ self.path += "/"
+ # Recurse into all blobs and subtrees
+ for m, s, p in self.parse_tree(data):
+ parser.push(s,
+ self.__class__(self.parser, self.cb, p, m))
+ elif t == "blob":
+ self.cb(self.path, self.mode, data)
+ else:
+ raise ValueError("Unknown object type '%s'" % (t))
+
+ self.push(tree_objspec, _ObjHandler(self, callback, prefix))
+ self.process()
+
+
+class GitRefMap(object):
+
+ """Map Git ref names to the Git object names they currently point to.
+
+ Behaves like a dictionary of Git ref names -> Git object names.
+
+ """
+
+ def __init__ (self, obj_fetcher):
+ """Create a new Git ref -> object map."""
+ self.obj_fetcher = obj_fetcher
+ self._cache = {} # dict: refname -> objname
+
+ def _load (self, ref):
+ """Retrieve the object currently bound to the given ref.
+
+ The name of the object pointed to by the given ref is stored
+ into this mapping, and also returned.
+
+ """
+ if ref not in self._cache:
+ self._cache[ref] = self.obj_fetcher.get_sha1(ref)
+ return self._cache[ref]
+
+ def __contains__ (self, refname):
+ """Return True if the given refname is present in this cache."""
+ return bool(self._load(refname))
+
+ def __getitem__ (self, refname):
+ """Return the git object name pointed to by the given refname."""
+ commit = self._load(refname)
+ if commit is None:
+ raise KeyError("Unknown ref '%s'" % (refname))
+ return commit
+
+ def get (self, refname, default = None):
+ """Return the git object name pointed to by the given refname."""
+ commit = self._load(refname)
+ if commit is None:
+ return default
+ return commit
+
+
+class GitFICommit(object):
+
+ """Encapsulate the data in a Git fast-import commit command."""
+
+ SHA1RE = re.compile(r'^[0-9a-f]{40}$')
+
+ @classmethod
+ def parse_mode (cls, mode):
+ """Verify the given git file mode, and return it as a string."""
+ assert mode in (644, 755, 100644, 100755, 120000)
+ return "%i" % (mode)
+
+ @classmethod
+ def parse_objname (cls, objname):
+ """Return the given object name (or mark number) as a string."""
+ if isinstance(objname, int): # Object name is a mark number
+ assert objname > 0
+ return ":%i" % (objname)
+
+ # No existence check is done, only checks for valid format
+ assert cls.SHA1RE.match(objname) # Object name is valid SHA1
+ return objname
+
+ @classmethod
+ def quote_path (cls, path):
+ """Return a quoted version of the given path."""
+ path = path.replace("\\", "\\\\")
+ path = path.replace("\n", "\\n")
+ path = path.replace('"', '\\"')
+ return '"%s"' % (path)
+
+ @classmethod
+ def parse_path (cls, path):
+ """Verify that the given path is valid, and quote it, if needed."""
+ assert not isinstance(path, int) # Cannot be a mark number
+
+ # These checks verify the rules on the fast-import man page
+ assert not path.count("//")
+ assert not path.endswith("/")
+ assert not path.startswith("/")
+ assert not path.count("/./")
+ assert not path.count("/../")
+ assert not path.endswith("/.")
+ assert not path.endswith("/..")
+ assert not path.startswith("./")
+ assert not path.startswith("../")
+
+ if path.count('"') + path.count('\n') + path.count('\\'):
+ return cls.quote_path(path)
+ return path
+
+ def __init__ (self, name, email, timestamp, timezone, message):
+ """Create a new Git fast-import commit, with the given metadata."""
+ self.name = name
+ self.email = email
+ self.timestamp = timestamp
+ self.timezone = timezone
+ self.message = message
+ self.pathops = [] # List of path operations in this commit
+
+ def modify (self, mode, blobname, path):
+ """Add a file modification to this Git fast-import commit."""
+ self.pathops.append(("M",
+ self.parse_mode(mode),
+ self.parse_objname(blobname),
+ self.parse_path(path)))
+
+ def delete (self, path):
+ """Add a file deletion to this Git fast-import commit."""
+ self.pathops.append(("D", self.parse_path(path)))
+
+ def copy (self, path, newpath):
+ """Add a file copy to this Git fast-import commit."""
+ self.pathops.append(("C",
+ self.parse_path(path),
+ self.parse_path(newpath)))
+
+ def rename (self, path, newpath):
+ """Add a file rename to this Git fast-import commit."""
+ self.pathops.append(("R",
+ self.parse_path(path),
+ self.parse_path(newpath)))
+
+ def note (self, blobname, commit):
+ """Add a note object to this Git fast-import commit."""
+ self.pathops.append(("N",
+ self.parse_objname(blobname),
+ self.parse_objname(commit)))
+
+ def deleteall (self):
+ """Delete all files in this Git fast-import commit."""
+ self.pathops.append("deleteall")
+
+
+class TestGitFICommit(unittest.TestCase):
+
+ """GitFICommit selftests."""
+
+ def test_basic (self):
+ """GitFICommit basic selftests."""
+
+ def expect_fail (method, data):
+ """Verify that the method(data) raises an AssertionError."""
+ try:
+ method(data)
+ except AssertionError:
+ return
+ raise AssertionError("Failed test for invalid data '%s(%s)'" %
+ (method.__name__, repr(data)))
+
+ def test_parse_mode (self):
+ """GitFICommit.parse_mode() selftests."""
+ self.assertEqual(GitFICommit.parse_mode(644), "644")
+ self.assertEqual(GitFICommit.parse_mode(755), "755")
+ self.assertEqual(GitFICommit.parse_mode(100644), "100644")
+ self.assertEqual(GitFICommit.parse_mode(100755), "100755")
+ self.assertEqual(GitFICommit.parse_mode(120000), "120000")
+ self.assertRaises(AssertionError, GitFICommit.parse_mode, 0)
+ self.assertRaises(AssertionError, GitFICommit.parse_mode, 123)
+ self.assertRaises(AssertionError, GitFICommit.parse_mode, 600)
+ self.assertRaises(AssertionError, GitFICommit.parse_mode, "644")
+ self.assertRaises(AssertionError, GitFICommit.parse_mode, "abc")
+
+ def test_parse_objname (self):
+ """GitFICommit.parse_objname() selftests."""
+ self.assertEqual(GitFICommit.parse_objname(1), ":1")
+ self.assertRaises(AssertionError, GitFICommit.parse_objname, 0)
+ self.assertRaises(AssertionError, GitFICommit.parse_objname, -1)
+ self.assertEqual(GitFICommit.parse_objname("0123456789" * 4),
+ "0123456789" * 4)
+ self.assertEqual(GitFICommit.parse_objname("2468abcdef" * 4),
+ "2468abcdef" * 4)
+ self.assertRaises(AssertionError, GitFICommit.parse_objname,
+ "abcdefghij" * 4)
+
+ def test_parse_path (self):
+ """GitFICommit.parse_path() selftests."""
+ self.assertEqual(GitFICommit.parse_path("foo/bar"), "foo/bar")
+ self.assertEqual(GitFICommit.parse_path("path/with\n and \" in it"),
+ '"path/with\\n and \\" in it"')
+ self.assertRaises(AssertionError, GitFICommit.parse_path, 1)
+ self.assertRaises(AssertionError, GitFICommit.parse_path, 0)
+ self.assertRaises(AssertionError, GitFICommit.parse_path, -1)
+ self.assertRaises(AssertionError, GitFICommit.parse_path, "foo//bar")
+ self.assertRaises(AssertionError, GitFICommit.parse_path, "foo/bar/")
+ self.assertRaises(AssertionError, GitFICommit.parse_path, "/foo/bar")
+ self.assertRaises(AssertionError, GitFICommit.parse_path, "foo/./bar")
+ self.assertRaises(AssertionError, GitFICommit.parse_path, "foo/../bar")
+ self.assertRaises(AssertionError, GitFICommit.parse_path, "foo/bar/.")
+ self.assertRaises(AssertionError, GitFICommit.parse_path, "foo/bar/..")
+ self.assertRaises(AssertionError, GitFICommit.parse_path, "./foo/bar")
+ self.assertRaises(AssertionError, GitFICommit.parse_path, "../foo/bar")
+
+
+class GitFastImport(object):
+
+ """Encapsulate communication with git fast-import."""
+
+ def __init__ (self, f, obj_fetcher, last_mark = 0):
+ """Set up self to communicate with a fast-import process through f."""
+ self.f = f # File object where fast-import stream is written
+ self.obj_fetcher = obj_fetcher # GitObjectFetcher instance
+ self.next_mark = last_mark + 1 # Next mark number
+ self.refs = set() # Keep track of the refnames we've seen
+
+ def comment (self, s):
+ """Write the given comment in the fast-import stream."""
+ assert "\n" not in s, "Malformed comment: '%s'" % (s)
+ self.f.write("# %s\n" % (s))
+
+ def commit (self, ref, commitdata):
+ """Make a commit on the given ref, with the given GitFICommit.
+
+ Return the mark number identifying this commit.
+
+ """
+ self.f.write("""\
+commit %(ref)s
+mark :%(mark)i
+committer %(name)s <%(email)s> %(timestamp)i %(timezone)s
+data %(msgLength)i
+%(msg)s
+""" % {
+ 'ref': ref,
+ 'mark': self.next_mark,
+ 'name': commitdata.name,
+ 'email': commitdata.email,
+ 'timestamp': commitdata.timestamp,
+ 'timezone': commitdata.timezone,
+ 'msgLength': len(commitdata.message),
+ 'msg': commitdata.message,
+})
+
+ if ref not in self.refs:
+ self.refs.add(ref)
+ parent = ref + "^0"
+ if self.obj_fetcher.get_sha1(parent):
+ self.f.write("from %s\n" % (parent))
+
+ for op in commitdata.pathops:
+ self.f.write(" ".join(op))
+ self.f.write("\n")
+ self.f.write("\n")
+ retval = self.next_mark
+ self.next_mark += 1
+ return retval
+
+ def blob (self, data):
+ """Import the given blob.
+
+ Return the mark number identifying this blob.
+
+ """
+ self.f.write("blob\nmark :%i\ndata %i\n%s\n" %
+ (self.next_mark, len(data), data))
+ retval = self.next_mark
+ self.next_mark += 1
+ return retval
+
+ def reset (self, ref, objname):
+ """Reset the given ref to point at the given Git object."""
+ self.f.write("reset %s\nfrom %s\n\n" %
+ (ref, GitFICommit.parse_objname(objname)))
+ if ref not in self.refs:
+ self.refs.add(ref)
+
+
+class GitNotes(object):
+
+ """Encapsulate access to Git notes.
+
+ Simulates a dictionary of object name (SHA1) -> Git note mappings.
+
+ """
+
+ def __init__ (self, notes_ref, obj_fetcher):
+ """Create a new Git notes interface, bound to the given notes ref."""
+ self.notes_ref = notes_ref
+ self.obj_fetcher = obj_fetcher # Used to get objects from repo
+ self.imports = [] # list: (objname, note data blob name) tuples
+
+ def __del__ (self):
+ """Verify that self.commit_notes() was called before destruction."""
+ if self.imports:
+ error("Missing call to self.commit_notes().")
+ error("%i notes are not committed!", len(self.imports))
+
+ def _load (self, objname):
+ """Return the note data associated with the given git object.
+
+ The note data is returned in string form. If no note is found
+ for the given object, None is returned.
+
+ """
+ try:
+ f = self.obj_fetcher.open_obj("%s:%s" % (self.notes_ref, objname))
+ ret = f.read()
+ f.close()
+ except KeyError:
+ ret = None
+ return ret
+
+ def __getitem__ (self, objname):
+ """Return the note contents associated with the given object.
+
+ Raise KeyError if given object has no associated note.
+
+ """
+ blobdata = self._load(objname)
+ if blobdata is None:
+ raise KeyError("Object '%s' has no note" % (objname))
+ return blobdata
+
+ def get (self, objname, default = None):
+ """Return the note contents associated with the given object.
+
+ Return given default if given object has no associated note.
+
+ """
+ blobdata = self._load(objname)
+ if blobdata is None:
+ return default
+ return blobdata
+
+ def import_note (self, objname, data, gfi):
+ """Tell git fast-import to store data as a note for objname.
+
+ This method uses the given GitFastImport object to create a
+ blob containing the given note data. Also an entry mapping the
+ given object name to the created blob is stored until
+ commit_notes() is called.
+
+ Note that this method only works if it is later followed by a
+ call to self.commit_notes() (which produces the note commit
+ that refers to the blob produced here).
+
+ """
+ if not data.endswith("\n"):
+ data += "\n"
+ gfi.comment("Importing note for object %s" % (objname))
+ mark = gfi.blob(data)
+ self.imports.append((objname, mark))
+
+ def commit_notes (self, gfi, author, message):
+ """Produce a git fast-import note commit for the imported notes.
+
+ This method uses the given GitFastImport object to create a
+ commit on the notes ref, introducing the notes previously
+ submitted to import_note().
+
+ """
+ if not self.imports:
+ return
+ commitdata = GitFICommit(author[0], author[1],
+ time.time(), "0000", message)
+ for objname, blobname in self.imports:
+ assert isinstance(objname, int) and objname > 0
+ assert isinstance(blobname, int) and blobname > 0
+ commitdata.note(blobname, objname)
+ gfi.commit(self.notes_ref, commitdata)
+ self.imports = []
+
+
+class GitCachedNotes(GitNotes):
+
+ """Encapsulate access to Git notes (cached version).
+
+ Only use this class if no caching is done at a higher level.
+
+ Simulates a dictionary of object name (SHA1) -> Git note mappings.
+
+ """
+
+ def __init__ (self, notes_ref, obj_fetcher):
+ """Set up a caching wrapper around GitNotes."""
+ GitNotes.__init__(self, notes_ref, obj_fetcher)
+ self._cache = {} # Cache: object name -> note data
+
+ def __del__ (self):
+ """Verify that GitNotes' destructor is called."""
+ GitNotes.__del__(self)
+
+ def _load (self, objname):
+ """Extend GitNotes._load() with a local objname -> note cache."""
+ if objname not in self._cache:
+ self._cache[objname] = GitNotes._load(self, objname)
+ return self._cache[objname]
+
+ def import_note (self, objname, data, gfi):
+ """Extend GitNotes.import_note() with a local objname -> note cache."""
+ if not data.endswith("\n"):
+ data += "\n"
+ assert objname not in self._cache
+ self._cache[objname] = data
+ GitNotes.import_note(self, objname, data, gfi)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/git_remote_helpers/setup.py b/git_remote_helpers/setup.py
new file mode 100644
index 0000000..4d434b6
--- /dev/null
+++ b/git_remote_helpers/setup.py
@@ -0,0 +1,17 @@
+#!/usr/bin/env python
+
+"""Distutils build/install script for the git_remote_helpers package."""
+
+from distutils.core import setup
+
+setup(
+ name = 'git_remote_helpers',
+ version = '0.1.0',
+ description = 'Git remote helper program for non-git repositories',
+ license = 'GPLv2',
+ author = 'The Git Community',
+ author_email = 'git@vger.kernel.org',
+ url = 'http://www.git-scm.com/',
+ package_dir = {'git_remote_helpers': ''},
+ packages = ['git_remote_helpers', 'git_remote_helpers.git'],
+)
diff --git a/git_remote_helpers/util.py b/git_remote_helpers/util.py
new file mode 100644
index 0000000..dce83e6
--- /dev/null
+++ b/git_remote_helpers/util.py
@@ -0,0 +1,194 @@
+#!/usr/bin/env python
+
+"""Misc. useful functionality used by the rest of this package.
+
+This module provides common functionality used by the other modules in
+this package.
+
+"""
+
+import sys
+import os
+import subprocess
+
+
+# Whether or not to show debug messages
+DEBUG = False
+
+def notify(msg, *args):
+ """Print a message to stderr."""
+ print >> sys.stderr, msg % args
+
+def debug (msg, *args):
+ """Print a debug message to stderr when DEBUG is enabled."""
+ if DEBUG:
+ print >> sys.stderr, msg % args
+
+def error (msg, *args):
+ """Print an error message to stderr."""
+ print >> sys.stderr, "ERROR:", msg % args
+
+def warn(msg, *args):
+ """Print a warning message to stderr."""
+ print >> sys.stderr, "warning:", msg % args
+
+def die (msg, *args):
+ """Print as error message to stderr and exit the program."""
+ error(msg, *args)
+ sys.exit(1)
+
+
+class ProgressIndicator(object):
+
+ """Simple progress indicator.
+
+ Displayed as a spinning character by default, but can be customized
+ by passing custom messages that overrides the spinning character.
+
+ """
+
+ States = ("|", "/", "-", "\\")
+
+ def __init__ (self, prefix = "", f = sys.stdout):
+ """Create a new ProgressIndicator, bound to the given file object."""
+ self.n = 0 # Simple progress counter
+ self.f = f # Progress is written to this file object
+ self.prev_len = 0 # Length of previous msg (to be overwritten)
+ self.prefix = prefix # Prefix prepended to each progress message
+ self.prefix_lens = [] # Stack of prefix string lengths
+
+ def pushprefix (self, prefix):
+ """Append the given prefix onto the prefix stack."""
+ self.prefix_lens.append(len(self.prefix))
+ self.prefix += prefix
+
+ def popprefix (self):
+ """Remove the last prefix from the prefix stack."""
+ prev_len = self.prefix_lens.pop()
+ self.prefix = self.prefix[:prev_len]
+
+ def __call__ (self, msg = None, lf = False):
+ """Indicate progress, possibly with a custom message."""
+ if msg is None:
+ msg = self.States[self.n % len(self.States)]
+ msg = self.prefix + msg
+ print >> self.f, "\r%-*s" % (self.prev_len, msg),
+ self.prev_len = len(msg.expandtabs())
+ if lf:
+ print >> self.f
+ self.prev_len = 0
+ self.n += 1
+
+ def finish (self, msg = "done", noprefix = False):
+ """Finalize progress indication with the given message."""
+ if noprefix:
+ self.prefix = ""
+ self(msg, True)
+
+
+def start_command (args, cwd = None, shell = False, add_env = None,
+ stdin = subprocess.PIPE, stdout = subprocess.PIPE,
+ stderr = subprocess.PIPE):
+ """Start the given command, and return a subprocess object.
+
+ This provides a simpler interface to the subprocess module.
+
+ """
+ env = None
+ if add_env is not None:
+ env = os.environ.copy()
+ env.update(add_env)
+ return subprocess.Popen(args, bufsize = 1, stdin = stdin, stdout = stdout,
+ stderr = stderr, cwd = cwd, shell = shell,
+ env = env, universal_newlines = True)
+
+
+def run_command (args, cwd = None, shell = False, add_env = None,
+ flag_error = True):
+ """Run the given command to completion, and return its results.
+
+ This provides a simpler interface to the subprocess module.
+
+ The results are formatted as a 3-tuple: (exit_code, output, errors)
+
+ If flag_error is enabled, Error messages will be produced if the
+ subprocess terminated with a non-zero exit code and/or stderr
+ output.
+
+ The other arguments are passed on to start_command().
+
+ """
+ process = start_command(args, cwd, shell, add_env)
+ (output, errors) = process.communicate()
+ exit_code = process.returncode
+ if flag_error and errors:
+ error("'%s' returned errors:\n---\n%s---", " ".join(args), errors)
+ if flag_error and exit_code:
+ error("'%s' returned exit code %i", " ".join(args), exit_code)
+ return (exit_code, output, errors)
+
+
+def file_reader_method (missing_ok = False):
+ """Decorator for simplifying reading of files.
+
+ If missing_ok is True, a failure to open a file for reading will
+ not raise the usual IOError, but instead the wrapped method will be
+ called with f == None. The method must in this case properly
+ handle f == None.
+
+ """
+ def _wrap (method):
+ """Teach given method to handle both filenames and file objects.
+
+ The given method must take a file object as its second argument
+ (the first argument being 'self', of course). This decorator
+ will take a filename given as the second argument and promote
+ it to a file object.
+
+ """
+ def _wrapped_method (self, filename, *args, **kwargs):
+ if isinstance(filename, file):
+ f = filename
+ else:
+ try:
+ f = open(filename, 'r')
+ except IOError:
+ if missing_ok:
+ f = None
+ else:
+ raise
+ try:
+ return method(self, f, *args, **kwargs)
+ finally:
+ if not isinstance(filename, file) and f:
+ f.close()
+ return _wrapped_method
+ return _wrap
+
+
+def file_writer_method (method):
+ """Decorator for simplifying writing of files.
+
+ Enables the given method to handle both filenames and file objects.
+
+ The given method must take a file object as its second argument
+ (the first argument being 'self', of course). This decorator will
+ take a filename given as the second argument and promote it to a
+ file object.
+
+ """
+ def _new_method (self, filename, *args, **kwargs):
+ if isinstance(filename, file):
+ f = filename
+ else:
+ # Make sure the containing directory exists
+ parent_dir = os.path.dirname(filename)
+ if not os.path.isdir(parent_dir):
+ os.makedirs(parent_dir)
+ f = open(filename, 'w')
+ try:
+ return method(self, f, *args, **kwargs)
+ finally:
+ if not isinstance(filename, file):
+ f.close()
+ return _new_method
diff --git a/t/test-lib.sh b/t/test-lib.sh
index 0b991db..6ed5b28 100644
--- a/t/test-lib.sh
+++ b/t/test-lib.sh
@@ -638,6 +638,15 @@ test -d ../templates/blt || {
error "You haven't built things yet, have you?"
}
+if test -z "$GIT_TEST_INSTALLED"
+then
+ GITPYTHONLIB="$(pwd)/../git_remote_helpers/build/lib"
+ export GITPYTHONLIB
+ test -d ../git_remote_helpers/build || {
+ error "You haven't built git_remote_helpers yet, have you?"
+ }
+fi
+
if ! test -x ../test-chmtime; then
echo >&2 'You need to build test-chmtime:'
echo >&2 'Run "make test-chmtime" in the source (toplevel) directory'
--
1.6.5.2.295.g0d105
^ permalink raw reply related
* [PATCH v2 12/13] Basic build infrastructure for Python scripts
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Johan Herland
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
From: Johan Herland <johan@herland.net>
This patch adds basic boilerplate support (based on corresponding Perl
sections) for enabling the building and installation Python scripts.
There are currently no Python scripts being built, and when Python
scripts are added in future patches, their building and installation
can be disabled by defining NO_PYTHON.
Signed-off-by: Johan Herland <johan@herland.net>
---
Unchanged.
Makefile | 13 +++++++++++++
configure.ac | 3 +++
t/test-lib.sh | 1 +
3 files changed, 17 insertions(+), 0 deletions(-)
diff --git a/Makefile b/Makefile
index 5d5976f..6d1593f 100644
--- a/Makefile
+++ b/Makefile
@@ -168,6 +168,8 @@ all::
#
# Define NO_PERL if you do not want Perl scripts or libraries at all.
#
+# Define NO_PYTHON if you do not want Python scripts or libraries at all.
+#
# Define NO_TCLTK if you do not want Tcl/Tk GUI.
#
# The TCL_PATH variable governs the location of the Tcl interpreter
@@ -312,6 +314,7 @@ LIB_H =
LIB_OBJS =
PROGRAMS =
SCRIPT_PERL =
+SCRIPT_PYTHON =
SCRIPT_SH =
TEST_PROGRAMS =
@@ -349,6 +352,7 @@ SCRIPT_PERL += git-svn.perl
SCRIPTS = $(patsubst %.sh,%,$(SCRIPT_SH)) \
$(patsubst %.perl,%,$(SCRIPT_PERL)) \
+ $(patsubst %.py,%,$(SCRIPT_PYTHON)) \
git-instaweb
# Empty...
@@ -402,8 +406,12 @@ endif
ifndef PERL_PATH
PERL_PATH = /usr/bin/perl
endif
+ifndef PYTHON_PATH
+ PYTHON_PATH = /usr/bin/python
+endif
export PERL_PATH
+export PYTHON_PATH
LIB_FILE=libgit.a
XDIFF_LIB=xdiff/lib.a
@@ -1315,6 +1323,10 @@ ifeq ($(PERL_PATH),)
NO_PERL=NoThanks
endif
+ifeq ($(PYTHON_PATH),)
+NO_PYTHON=NoThanks
+endif
+
QUIET_SUBDIR0 = +$(MAKE) -C # space to separate -C and subdir
QUIET_SUBDIR1 =
@@ -1362,6 +1374,7 @@ prefix_SQ = $(subst ','\'',$(prefix))
SHELL_PATH_SQ = $(subst ','\'',$(SHELL_PATH))
PERL_PATH_SQ = $(subst ','\'',$(PERL_PATH))
+PYTHON_PATH_SQ = $(subst ','\'',$(PYTHON_PATH))
TCLTK_PATH_SQ = $(subst ','\'',$(TCLTK_PATH))
LIBS = $(GITLIBS) $(EXTLIBS)
diff --git a/configure.ac b/configure.ac
index b09b8e4..84b6cf4 100644
--- a/configure.ac
+++ b/configure.ac
@@ -233,6 +233,9 @@ GIT_ARG_SET_PATH(shell)
# Define PERL_PATH to provide path to Perl.
GIT_ARG_SET_PATH(perl)
#
+# Define PYTHON_PATH to provide path to Python.
+GIT_ARG_SET_PATH(python)
+#
# Define ZLIB_PATH to provide path to zlib.
GIT_ARG_SET_PATH(zlib)
#
diff --git a/t/test-lib.sh b/t/test-lib.sh
index f2ca536..0b991db 100644
--- a/t/test-lib.sh
+++ b/t/test-lib.sh
@@ -729,6 +729,7 @@ case $(uname -s) in
esac
test -z "$NO_PERL" && test_set_prereq PERL
+test -z "$NO_PYTHON" && test_set_prereq PYTHON
# test whether the filesystem supports symbolic links
ln -s x y 2>/dev/null && test -h y 2>/dev/null && test_set_prereq SYMLINKS
--
1.6.5.2.295.g0d105
^ permalink raw reply related
* [PATCH v2 10/13] Allow helpers to report in "list" command that the ref is unchanged
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Daniel Barkalow
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
From: Daniel Barkalow <barkalow@iabervon.org>
Helpers may use a line like "? name unchanged" to specify that there
is nothing new at that name, without any git-specific code to
determine the correct response.
Signed-off-by: Daniel Barkalow <barkalow@iabervon.org>
---
Unchanged.
Documentation/git-remote-helpers.txt | 4 +++-
transport-helper.c | 22 ++++++++++++++++++++++
2 files changed, 25 insertions(+), 1 deletions(-)
diff --git a/Documentation/git-remote-helpers.txt b/Documentation/git-remote-helpers.txt
index e9aa67e..2c5130f 100644
--- a/Documentation/git-remote-helpers.txt
+++ b/Documentation/git-remote-helpers.txt
@@ -70,7 +70,9 @@ CAPABILITIES
REF LIST ATTRIBUTES
-------------------
-None are defined yet, but the caller must accept any which are supplied.
+'unchanged'::
+ This ref is unchanged since the last import or fetch, although
+ the helper cannot necessarily determine what value that produced.
Documentation
-------------
diff --git a/transport-helper.c b/transport-helper.c
index 72ed95b..a80d803 100644
--- a/transport-helper.c
+++ b/transport-helper.c
@@ -176,6 +176,22 @@ static int fetch(struct transport *transport,
return -1;
}
+static int has_attribute(const char *attrs, const char *attr) {
+ int len;
+ if (!attrs)
+ return 0;
+
+ len = strlen(attr);
+ for (;;) {
+ const char *space = strchrnul(attrs, ' ');
+ if (len == space - attrs && !strncmp(attrs, attr, len))
+ return 1;
+ if (!*space)
+ return 0;
+ attrs = space + 1;
+ }
+}
+
static struct ref *get_refs_list(struct transport *transport, int for_push)
{
struct child_process *helper;
@@ -210,6 +226,12 @@ static struct ref *get_refs_list(struct transport *transport, int for_push)
(*tail)->symref = xstrdup(buf.buf + 1);
else if (buf.buf[0] != '?')
get_sha1_hex(buf.buf, (*tail)->old_sha1);
+ if (eon) {
+ if (has_attribute(eon + 1, "unchanged")) {
+ (*tail)->status |= REF_STATUS_UPTODATE;
+ read_ref((*tail)->name, (*tail)->old_sha1);
+ }
+ }
tail = &((*tail)->next);
}
strbuf_release(&buf);
--
1.6.5.2.295.g0d105
^ permalink raw reply related
* [PATCH v2 07/13] Add support for "import" helper command
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Daniel Barkalow, Sverre Rabbelier
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
From: Daniel Barkalow <barkalow@iabervon.org>
This command, supported if the "import" capability is advertized,
allows a helper to support fetching by outputting a git-fast-import
stream.
If both "fetch" and "import" are advertized, git itself will use
"fetch" (although other users may use "import" in this case).
Signed-off-by: Daniel Barkalow <barkalow@iabervon.org>
Signed-off-by: Sverre Rabbelier <srabbelier@gmail.com>
---
Undid the change to the read_ref line, see patch 0009 for a
suggested proper fix.
Documentation/git-remote-helpers.txt | 10 ++++++
transport-helper.c | 52 ++++++++++++++++++++++++++++++++++
2 files changed, 62 insertions(+), 0 deletions(-)
diff --git a/Documentation/git-remote-helpers.txt b/Documentation/git-remote-helpers.txt
index 173ee23..e9aa67e 100644
--- a/Documentation/git-remote-helpers.txt
+++ b/Documentation/git-remote-helpers.txt
@@ -43,6 +43,13 @@ Commands are given by the caller on the helper's standard input, one per line.
+
Supported if the helper has the "fetch" capability.
+'import' <name>::
+ Produces a fast-import stream which imports the current value
+ of the named ref. It may additionally import other refs as
+ needed to construct the history efficiently.
++
+Supported if the helper has the "import" capability.
+
If a fatal error occurs, the program writes the error message to
stderr and exits. The caller should expect that a suitable error
message has been printed if the child closes the connection without
@@ -57,6 +64,9 @@ CAPABILITIES
'fetch'::
This helper supports the 'fetch' command.
+'import'::
+ This helper supports the 'import' command.
+
REF LIST ATTRIBUTES
-------------------
diff --git a/transport-helper.c b/transport-helper.c
index 53d8f08..82caaae 100644
--- a/transport-helper.c
+++ b/transport-helper.c
@@ -11,6 +11,7 @@ struct helper_data
const char *name;
struct child_process *helper;
unsigned fetch : 1;
+ unsigned import : 1;
};
static struct child_process *get_helper(struct transport *transport)
@@ -48,6 +49,8 @@ static struct child_process *get_helper(struct transport *transport)
break;
if (!strcmp(buf.buf, "fetch"))
data->fetch = 1;
+ if (!strcmp(buf.buf, "import"))
+ data->import = 1;
}
return data->helper;
}
@@ -98,6 +101,52 @@ static int fetch_with_fetch(struct transport *transport,
return 0;
}
+static int get_importer(struct transport *transport, struct child_process *fastimport)
+{
+ struct child_process *helper = get_helper(transport);
+ memset(fastimport, 0, sizeof(*fastimport));
+ fastimport->in = helper->out;
+ fastimport->argv = xcalloc(5, sizeof(*fastimport->argv));
+ fastimport->argv[0] = "fast-import";
+ fastimport->argv[1] = "--quiet";
+
+ fastimport->git_cmd = 1;
+ return start_command(fastimport);
+}
+
+static int fetch_with_import(struct transport *transport,
+ int nr_heads, struct ref **to_fetch)
+{
+ struct child_process fastimport;
+ struct child_process *helper = get_helper(transport);
+ int i;
+ struct ref *posn;
+ struct strbuf buf = STRBUF_INIT;
+
+ if (get_importer(transport, &fastimport))
+ die("Couldn't run fast-import");
+
+ for (i = 0; i < nr_heads; i++) {
+ posn = to_fetch[i];
+ if (posn->status & REF_STATUS_UPTODATE)
+ continue;
+
+ strbuf_addf(&buf, "import %s\n", posn->name);
+ write_in_full(helper->in, buf.buf, buf.len);
+ strbuf_reset(&buf);
+ }
+ disconnect_helper(transport);
+ finish_command(&fastimport);
+
+ for (i = 0; i < nr_heads; i++) {
+ posn = to_fetch[i];
+ if (posn->status & REF_STATUS_UPTODATE)
+ continue;
+ read_ref(posn->name, posn->old_sha1);
+ }
+ return 0;
+}
+
static int fetch(struct transport *transport,
int nr_heads, struct ref **to_fetch)
{
@@ -115,6 +164,9 @@ static int fetch(struct transport *transport,
if (data->fetch)
return fetch_with_fetch(transport, nr_heads, to_fetch);
+ if (data->import)
+ return fetch_with_import(transport, nr_heads, to_fetch);
+
return -1;
}
--
1.6.5.2.295.g0d105
^ permalink raw reply related
* [PATCH v2 09/13] Honour the refspec when updating refs after import
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Sverre Rabbelier
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
This way the helper can write to 'refs/remotes/origin/*' instead of
writing to 'refs/heads/*'.
Signed-off-by: Sverre Rabbelier <srabbelier@gmail.com>
---
Daniel, does this look good to you?
Let's assume the following:
* list: only HEAD is a symref (to refs/heads/<branch>), all other
refs are '? refs/heads/<branch>'.
* import: the helper creates branches under refs/remotes/<alias>/*
(since the refspec code is not yet in that would allow
it to create them under refs/<vcs>/<alias>/*)
Now when updating the refs we do the following:
transport-helper.c:145 "read_ref(posn->name, posn->old_sha1);"
The value of posn->name looks like "refs/heads/<branch>". So what
does this lookup do? It tries to lookup the new value of the ref
_where it will be created_, this fails of course, since the ref
currently only exists as "refs/remotes/origin/<branch>". So, we
should instead be doing a lookup using posn->peer_ref->name, and
not do a lookup at all if it posn->peer_ref is not set (which
should not occur as we are passed only wanted peer refs).
Please let me know if this makes sense and both this and 0008 can
be squashed with 0007.
transport-helper.c | 5 ++++-
1 files changed, 4 insertions(+), 1 deletions(-)
diff --git a/transport-helper.c b/transport-helper.c
index 148496c..72ed95b 100644
--- a/transport-helper.c
+++ b/transport-helper.c
@@ -142,7 +142,10 @@ static int fetch_with_import(struct transport *transport,
posn = to_fetch[i];
if (posn->status & REF_STATUS_UPTODATE)
continue;
- read_ref(posn->name, posn->old_sha1);
+ if(posn->peer_ref) {
+ read_ref(posn->peer_ref->name, posn->peer_ref->old_sha1);
+ hashcpy(posn->old_sha1, posn->peer_ref->old_sha1);
+ }
}
return 0;
}
--
1.6.5.2.295.g0d105
^ permalink raw reply related
* [PATCH v2 05/13] Add a config option for remotes to specify a foreign vcs
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Daniel Barkalow, Sverre Rabbelier
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
From: Daniel Barkalow <barkalow@iabervon.org>
If this is set, the url is not required, and the transport always uses
a helper named "git-remote-<value>".
It is a separate configuration option in order to allow a sensible
configuration for foreign systems which either have no meaningful urls
for repositories or which require urls that do not specify the system
used by the repository at that location. However, this only affects
how the name of the helper is determined, not anything about the
interaction with the helper, and the contruction is such that, if the
foreign scm does happen to use a co-named url method, a url with that
method may be used directly.
Signed-off-by: Daniel Barkalow <barkalow@iabervon.org>
Signed-off-by: Sverre Rabbelier <srabbelier@gmail.com>
---
Unchanged.
Documentation/config.txt | 4 ++++
remote.c | 4 +++-
remote.h | 2 ++
transport.c | 5 +++++
4 files changed, 14 insertions(+), 1 deletions(-)
diff --git a/Documentation/config.txt b/Documentation/config.txt
index d1e2120..0d9d369 100644
--- a/Documentation/config.txt
+++ b/Documentation/config.txt
@@ -1408,6 +1408,10 @@ remote.<name>.tagopt::
Setting this value to \--no-tags disables automatic tag following when
fetching from remote <name>
+remote.<name>.vcs::
+ Setting this to a value <vcs> will cause git to interact with
+ the remote with the git-remote-<vcs> helper.
+
remotes.<group>::
The list of remotes which are fetched by "git remote update
<group>". See linkgit:git-remote[1].
diff --git a/remote.c b/remote.c
index 15c9cec..09bb79c 100644
--- a/remote.c
+++ b/remote.c
@@ -54,7 +54,7 @@ static char buffer[BUF_SIZE];
static int valid_remote(const struct remote *remote)
{
- return !!remote->url;
+ return (!!remote->url) || (!!remote->foreign_vcs);
}
static const char *alias_url(const char *url, struct rewrites *r)
@@ -444,6 +444,8 @@ static int handle_config(const char *key, const char *value, void *cb)
} else if (!strcmp(subkey, ".proxy")) {
return git_config_string((const char **)&remote->http_proxy,
key, value);
+ } else if (!strcmp(subkey, ".vcs")) {
+ return git_config_string(&remote->foreign_vcs, key, value);
}
return 0;
}
diff --git a/remote.h b/remote.h
index 5db8420..ac0ce2f 100644
--- a/remote.h
+++ b/remote.h
@@ -11,6 +11,8 @@ struct remote {
const char *name;
int origin;
+ const char *foreign_vcs;
+
const char **url;
int url_nr;
int url_alloc;
diff --git a/transport.c b/transport.c
index 5ae8db6..13bab4e 100644
--- a/transport.c
+++ b/transport.c
@@ -818,6 +818,11 @@ struct transport *transport_get(struct remote *remote, const char *url)
url = remote->url[0];
ret->url = url;
+ if (remote && remote->foreign_vcs) {
+ transport_helper_init(ret, remote->foreign_vcs);
+ return ret;
+ }
+
if (!prefixcmp(url, "rsync:")) {
ret->get_refs_list = get_refs_via_rsync;
ret->fetch = fetch_objs_via_rsync;
--
1.6.5.2.295.g0d105
^ permalink raw reply related
* [PATCH v2 06/13] Allow specifying the remote helper in the url
From: Sverre Rabbelier @ 2009-11-04 19:48 UTC (permalink / raw)
To: Git List, Johannes Schindelin, Daniel Barkalow, Johan Herland
Cc: Johannes Schindelin, Sverre Rabbelier
In-Reply-To: <1257364098-1685-1-git-send-email-srabbelier@gmail.com>
From: Johannes Schindelin <johannes.schindelin@gmx.de>
The common case for remote helpers will be to import some repository
which can be specified by a single URL. Support this use case by
allowing users to say:
git clone hg::https://soc.googlecode.com/hg/ soc
Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
Signed-off-by: Sverre Rabbelier <srabbelier@gmail.com>
---
Reworded commit message to be more neutral.
transport.c | 10 ++++++++++
1 files changed, 10 insertions(+), 0 deletions(-)
diff --git a/transport.c b/transport.c
index 13bab4e..5d814b5 100644
--- a/transport.c
+++ b/transport.c
@@ -818,6 +818,16 @@ struct transport *transport_get(struct remote *remote, const char *url)
url = remote->url[0];
ret->url = url;
+ /* maybe it is a foreign URL? */
+ if (url) {
+ const char *p = url;
+
+ while (isalnum(*p))
+ p++;
+ if (!prefixcmp(p, "::"))
+ remote->foreign_vcs = xstrndup(url, p - url);
+ }
+
if (remote && remote->foreign_vcs) {
transport_helper_init(ret, remote->foreign_vcs);
return ret;
--
1.6.5.2.295.g0d105
^ permalink raw reply related
page: next (older) | prev (newer) | latest
- recent:[subjects (threaded)|topics (new)|topics (active)]
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox