Merge lp:~ubuntuone-control-tower/ubuntu/karmic/desktopcouch/spb into lp:ubuntu/karmic/desktopcouch

Proposed by Chad Miller
Status: Merged
Merge reported by: James Westby
Merged at revision: not available
Proposed branch: lp:~ubuntuone-control-tower/ubuntu/karmic/desktopcouch/spb
Merge into: lp:ubuntu/karmic/desktopcouch
Diff against target: None lines
To merge this branch: bzr merge lp:~ubuntuone-control-tower/ubuntu/karmic/desktopcouch/spb
Reviewer Review Type Date Requested Status
James Westby (community) Approve
Review via email: mp+11017@code.launchpad.net
To post a comment you must log in.
Revision history for this message
Chad Miller (cmiller) wrote :

New upstream bugfix-only release.

Revision history for this message
James Westby (james-w) wrote :

Hi,

The watch file doesn't match the tarball name for this release.
If you are going to name the tarball like this then you should
update the watch file.

Uploading anyway, as this is for the alpha. Please correct for the
next upload.

Thanks,

James

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== added file 'COPYING'
2--- COPYING 1970-01-01 00:00:00 +0000
3+++ COPYING 2009-07-09 20:17:15 +0000
4@@ -0,0 +1,676 @@
5+
6+ GNU GENERAL PUBLIC LICENSE
7+ Version 3, 29 June 2007
8+
9+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
10+ Everyone is permitted to copy and distribute verbatim copies
11+ of this license document, but changing it is not allowed.
12+
13+ Preamble
14+
15+ The GNU General Public License is a free, copyleft license for
16+software and other kinds of works.
17+
18+ The licenses for most software and other practical works are designed
19+to take away your freedom to share and change the works. By contrast,
20+the GNU General Public License is intended to guarantee your freedom to
21+share and change all versions of a program--to make sure it remains free
22+software for all its users. We, the Free Software Foundation, use the
23+GNU General Public License for most of our software; it applies also to
24+any other work released this way by its authors. You can apply it to
25+your programs, too.
26+
27+ When we speak of free software, we are referring to freedom, not
28+price. Our General Public Licenses are designed to make sure that you
29+have the freedom to distribute copies of free software (and charge for
30+them if you wish), that you receive source code or can get it if you
31+want it, that you can change the software or use pieces of it in new
32+free programs, and that you know you can do these things.
33+
34+ To protect your rights, we need to prevent others from denying you
35+these rights or asking you to surrender the rights. Therefore, you have
36+certain responsibilities if you distribute copies of the software, or if
37+you modify it: responsibilities to respect the freedom of others.
38+
39+ For example, if you distribute copies of such a program, whether
40+gratis or for a fee, you must pass on to the recipients the same
41+freedoms that you received. You must make sure that they, too, receive
42+or can get the source code. And you must show them these terms so they
43+know their rights.
44+
45+ Developers that use the GNU GPL protect your rights with two steps:
46+(1) assert copyright on the software, and (2) offer you this License
47+giving you legal permission to copy, distribute and/or modify it.
48+
49+ For the developers' and authors' protection, the GPL clearly explains
50+that there is no warranty for this free software. For both users' and
51+authors' sake, the GPL requires that modified versions be marked as
52+changed, so that their problems will not be attributed erroneously to
53+authors of previous versions.
54+
55+ Some devices are designed to deny users access to install or run
56+modified versions of the software inside them, although the manufacturer
57+can do so. This is fundamentally incompatible with the aim of
58+protecting users' freedom to change the software. The systematic
59+pattern of such abuse occurs in the area of products for individuals to
60+use, which is precisely where it is most unacceptable. Therefore, we
61+have designed this version of the GPL to prohibit the practice for those
62+products. If such problems arise substantially in other domains, we
63+stand ready to extend this provision to those domains in future versions
64+of the GPL, as needed to protect the freedom of users.
65+
66+ Finally, every program is threatened constantly by software patents.
67+States should not allow patents to restrict development and use of
68+software on general-purpose computers, but in those that do, we wish to
69+avoid the special danger that patents applied to a free program could
70+make it effectively proprietary. To prevent this, the GPL assures that
71+patents cannot be used to render the program non-free.
72+
73+ The precise terms and conditions for copying, distribution and
74+modification follow.
75+
76+ TERMS AND CONDITIONS
77+
78+ 0. Definitions.
79+
80+ "This License" refers to version 3 of the GNU General Public License.
81+
82+ "Copyright" also means copyright-like laws that apply to other kinds of
83+works, such as semiconductor masks.
84+
85+ "The Program" refers to any copyrightable work licensed under this
86+License. Each licensee is addressed as "you". "Licensees" and
87+"recipients" may be individuals or organizations.
88+
89+ To "modify" a work means to copy from or adapt all or part of the work
90+in a fashion requiring copyright permission, other than the making of an
91+exact copy. The resulting work is called a "modified version" of the
92+earlier work or a work "based on" the earlier work.
93+
94+ A "covered work" means either the unmodified Program or a work based
95+on the Program.
96+
97+ To "propagate" a work means to do anything with it that, without
98+permission, would make you directly or secondarily liable for
99+infringement under applicable copyright law, except executing it on a
100+computer or modifying a private copy. Propagation includes copying,
101+distribution (with or without modification), making available to the
102+public, and in some countries other activities as well.
103+
104+ To "convey" a work means any kind of propagation that enables other
105+parties to make or receive copies. Mere interaction with a user through
106+a computer network, with no transfer of a copy, is not conveying.
107+
108+ An interactive user interface displays "Appropriate Legal Notices"
109+to the extent that it includes a convenient and prominently visible
110+feature that (1) displays an appropriate copyright notice, and (2)
111+tells the user that there is no warranty for the work (except to the
112+extent that warranties are provided), that licensees may convey the
113+work under this License, and how to view a copy of this License. If
114+the interface presents a list of user commands or options, such as a
115+menu, a prominent item in the list meets this criterion.
116+
117+ 1. Source Code.
118+
119+ The "source code" for a work means the preferred form of the work
120+for making modifications to it. "Object code" means any non-source
121+form of a work.
122+
123+ A "Standard Interface" means an interface that either is an official
124+standard defined by a recognized standards body, or, in the case of
125+interfaces specified for a particular programming language, one that
126+is widely used among developers working in that language.
127+
128+ The "System Libraries" of an executable work include anything, other
129+than the work as a whole, that (a) is included in the normal form of
130+packaging a Major Component, but which is not part of that Major
131+Component, and (b) serves only to enable use of the work with that
132+Major Component, or to implement a Standard Interface for which an
133+implementation is available to the public in source code form. A
134+"Major Component", in this context, means a major essential component
135+(kernel, window system, and so on) of the specific operating system
136+(if any) on which the executable work runs, or a compiler used to
137+produce the work, or an object code interpreter used to run it.
138+
139+ The "Corresponding Source" for a work in object code form means all
140+the source code needed to generate, install, and (for an executable
141+work) run the object code and to modify the work, including scripts to
142+control those activities. However, it does not include the work's
143+System Libraries, or general-purpose tools or generally available free
144+programs which are used unmodified in performing those activities but
145+which are not part of the work. For example, Corresponding Source
146+includes interface definition files associated with source files for
147+the work, and the source code for shared libraries and dynamically
148+linked subprograms that the work is specifically designed to require,
149+such as by intimate data communication or control flow between those
150+subprograms and other parts of the work.
151+
152+ The Corresponding Source need not include anything that users
153+can regenerate automatically from other parts of the Corresponding
154+Source.
155+
156+ The Corresponding Source for a work in source code form is that
157+same work.
158+
159+ 2. Basic Permissions.
160+
161+ All rights granted under this License are granted for the term of
162+copyright on the Program, and are irrevocable provided the stated
163+conditions are met. This License explicitly affirms your unlimited
164+permission to run the unmodified Program. The output from running a
165+covered work is covered by this License only if the output, given its
166+content, constitutes a covered work. This License acknowledges your
167+rights of fair use or other equivalent, as provided by copyright law.
168+
169+ You may make, run and propagate covered works that you do not
170+convey, without conditions so long as your license otherwise remains
171+in force. You may convey covered works to others for the sole purpose
172+of having them make modifications exclusively for you, or provide you
173+with facilities for running those works, provided that you comply with
174+the terms of this License in conveying all material for which you do
175+not control copyright. Those thus making or running the covered works
176+for you must do so exclusively on your behalf, under your direction
177+and control, on terms that prohibit them from making any copies of
178+your copyrighted material outside their relationship with you.
179+
180+ Conveying under any other circumstances is permitted solely under
181+the conditions stated below. Sublicensing is not allowed; section 10
182+makes it unnecessary.
183+
184+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
185+
186+ No covered work shall be deemed part of an effective technological
187+measure under any applicable law fulfilling obligations under article
188+11 of the WIPO copyright treaty adopted on 20 December 1996, or
189+similar laws prohibiting or restricting circumvention of such
190+measures.
191+
192+ When you convey a covered work, you waive any legal power to forbid
193+circumvention of technological measures to the extent such circumvention
194+is effected by exercising rights under this License with respect to
195+the covered work, and you disclaim any intention to limit operation or
196+modification of the work as a means of enforcing, against the work's
197+users, your or third parties' legal rights to forbid circumvention of
198+technological measures.
199+
200+ 4. Conveying Verbatim Copies.
201+
202+ You may convey verbatim copies of the Program's source code as you
203+receive it, in any medium, provided that you conspicuously and
204+appropriately publish on each copy an appropriate copyright notice;
205+keep intact all notices stating that this License and any
206+non-permissive terms added in accord with section 7 apply to the code;
207+keep intact all notices of the absence of any warranty; and give all
208+recipients a copy of this License along with the Program.
209+
210+ You may charge any price or no price for each copy that you convey,
211+and you may offer support or warranty protection for a fee.
212+
213+ 5. Conveying Modified Source Versions.
214+
215+ You may convey a work based on the Program, or the modifications to
216+produce it from the Program, in the form of source code under the
217+terms of section 4, provided that you also meet all of these conditions:
218+
219+ a) The work must carry prominent notices stating that you modified
220+ it, and giving a relevant date.
221+
222+ b) The work must carry prominent notices stating that it is
223+ released under this License and any conditions added under section
224+ 7. This requirement modifies the requirement in section 4 to
225+ "keep intact all notices".
226+
227+ c) You must license the entire work, as a whole, under this
228+ License to anyone who comes into possession of a copy. This
229+ License will therefore apply, along with any applicable section 7
230+ additional terms, to the whole of the work, and all its parts,
231+ regardless of how they are packaged. This License gives no
232+ permission to license the work in any other way, but it does not
233+ invalidate such permission if you have separately received it.
234+
235+ d) If the work has interactive user interfaces, each must display
236+ Appropriate Legal Notices; however, if the Program has interactive
237+ interfaces that do not display Appropriate Legal Notices, your
238+ work need not make them do so.
239+
240+ A compilation of a covered work with other separate and independent
241+works, which are not by their nature extensions of the covered work,
242+and which are not combined with it such as to form a larger program,
243+in or on a volume of a storage or distribution medium, is called an
244+"aggregate" if the compilation and its resulting copyright are not
245+used to limit the access or legal rights of the compilation's users
246+beyond what the individual works permit. Inclusion of a covered work
247+in an aggregate does not cause this License to apply to the other
248+parts of the aggregate.
249+
250+ 6. Conveying Non-Source Forms.
251+
252+ You may convey a covered work in object code form under the terms
253+of sections 4 and 5, provided that you also convey the
254+machine-readable Corresponding Source under the terms of this License,
255+in one of these ways:
256+
257+ a) Convey the object code in, or embodied in, a physical product
258+ (including a physical distribution medium), accompanied by the
259+ Corresponding Source fixed on a durable physical medium
260+ customarily used for software interchange.
261+
262+ b) Convey the object code in, or embodied in, a physical product
263+ (including a physical distribution medium), accompanied by a
264+ written offer, valid for at least three years and valid for as
265+ long as you offer spare parts or customer support for that product
266+ model, to give anyone who possesses the object code either (1) a
267+ copy of the Corresponding Source for all the software in the
268+ product that is covered by this License, on a durable physical
269+ medium customarily used for software interchange, for a price no
270+ more than your reasonable cost of physically performing this
271+ conveying of source, or (2) access to copy the
272+ Corresponding Source from a network server at no charge.
273+
274+ c) Convey individual copies of the object code with a copy of the
275+ written offer to provide the Corresponding Source. This
276+ alternative is allowed only occasionally and noncommercially, and
277+ only if you received the object code with such an offer, in accord
278+ with subsection 6b.
279+
280+ d) Convey the object code by offering access from a designated
281+ place (gratis or for a charge), and offer equivalent access to the
282+ Corresponding Source in the same way through the same place at no
283+ further charge. You need not require recipients to copy the
284+ Corresponding Source along with the object code. If the place to
285+ copy the object code is a network server, the Corresponding Source
286+ may be on a different server (operated by you or a third party)
287+ that supports equivalent copying facilities, provided you maintain
288+ clear directions next to the object code saying where to find the
289+ Corresponding Source. Regardless of what server hosts the
290+ Corresponding Source, you remain obligated to ensure that it is
291+ available for as long as needed to satisfy these requirements.
292+
293+ e) Convey the object code using peer-to-peer transmission, provided
294+ you inform other peers where the object code and Corresponding
295+ Source of the work are being offered to the general public at no
296+ charge under subsection 6d.
297+
298+ A separable portion of the object code, whose source code is excluded
299+from the Corresponding Source as a System Library, need not be
300+included in conveying the object code work.
301+
302+ A "User Product" is either (1) a "consumer product", which means any
303+tangible personal property which is normally used for personal, family,
304+or household purposes, or (2) anything designed or sold for incorporation
305+into a dwelling. In determining whether a product is a consumer product,
306+doubtful cases shall be resolved in favor of coverage. For a particular
307+product received by a particular user, "normally used" refers to a
308+typical or common use of that class of product, regardless of the status
309+of the particular user or of the way in which the particular user
310+actually uses, or expects or is expected to use, the product. A product
311+is a consumer product regardless of whether the product has substantial
312+commercial, industrial or non-consumer uses, unless such uses represent
313+the only significant mode of use of the product.
314+
315+ "Installation Information" for a User Product means any methods,
316+procedures, authorization keys, or other information required to install
317+and execute modified versions of a covered work in that User Product from
318+a modified version of its Corresponding Source. The information must
319+suffice to ensure that the continued functioning of the modified object
320+code is in no case prevented or interfered with solely because
321+modification has been made.
322+
323+ If you convey an object code work under this section in, or with, or
324+specifically for use in, a User Product, and the conveying occurs as
325+part of a transaction in which the right of possession and use of the
326+User Product is transferred to the recipient in perpetuity or for a
327+fixed term (regardless of how the transaction is characterized), the
328+Corresponding Source conveyed under this section must be accompanied
329+by the Installation Information. But this requirement does not apply
330+if neither you nor any third party retains the ability to install
331+modified object code on the User Product (for example, the work has
332+been installed in ROM).
333+
334+ The requirement to provide Installation Information does not include a
335+requirement to continue to provide support service, warranty, or updates
336+for a work that has been modified or installed by the recipient, or for
337+the User Product in which it has been modified or installed. Access to a
338+network may be denied when the modification itself materially and
339+adversely affects the operation of the network or violates the rules and
340+protocols for communication across the network.
341+
342+ Corresponding Source conveyed, and Installation Information provided,
343+in accord with this section must be in a format that is publicly
344+documented (and with an implementation available to the public in
345+source code form), and must require no special password or key for
346+unpacking, reading or copying.
347+
348+ 7. Additional Terms.
349+
350+ "Additional permissions" are terms that supplement the terms of this
351+License by making exceptions from one or more of its conditions.
352+Additional permissions that are applicable to the entire Program shall
353+be treated as though they were included in this License, to the extent
354+that they are valid under applicable law. If additional permissions
355+apply only to part of the Program, that part may be used separately
356+under those permissions, but the entire Program remains governed by
357+this License without regard to the additional permissions.
358+
359+ When you convey a copy of a covered work, you may at your option
360+remove any additional permissions from that copy, or from any part of
361+it. (Additional permissions may be written to require their own
362+removal in certain cases when you modify the work.) You may place
363+additional permissions on material, added by you to a covered work,
364+for which you have or can give appropriate copyright permission.
365+
366+ Notwithstanding any other provision of this License, for material you
367+add to a covered work, you may (if authorized by the copyright holders of
368+that material) supplement the terms of this License with terms:
369+
370+ a) Disclaiming warranty or limiting liability differently from the
371+ terms of sections 15 and 16 of this License; or
372+
373+ b) Requiring preservation of specified reasonable legal notices or
374+ author attributions in that material or in the Appropriate Legal
375+ Notices displayed by works containing it; or
376+
377+ c) Prohibiting misrepresentation of the origin of that material, or
378+ requiring that modified versions of such material be marked in
379+ reasonable ways as different from the original version; or
380+
381+ d) Limiting the use for publicity purposes of names of licensors or
382+ authors of the material; or
383+
384+ e) Declining to grant rights under trademark law for use of some
385+ trade names, trademarks, or service marks; or
386+
387+ f) Requiring indemnification of licensors and authors of that
388+ material by anyone who conveys the material (or modified versions of
389+ it) with contractual assumptions of liability to the recipient, for
390+ any liability that these contractual assumptions directly impose on
391+ those licensors and authors.
392+
393+ All other non-permissive additional terms are considered "further
394+restrictions" within the meaning of section 10. If the Program as you
395+received it, or any part of it, contains a notice stating that it is
396+governed by this License along with a term that is a further
397+restriction, you may remove that term. If a license document contains
398+a further restriction but permits relicensing or conveying under this
399+License, you may add to a covered work material governed by the terms
400+of that license document, provided that the further restriction does
401+not survive such relicensing or conveying.
402+
403+ If you add terms to a covered work in accord with this section, you
404+must place, in the relevant source files, a statement of the
405+additional terms that apply to those files, or a notice indicating
406+where to find the applicable terms.
407+
408+ Additional terms, permissive or non-permissive, may be stated in the
409+form of a separately written license, or stated as exceptions;
410+the above requirements apply either way.
411+
412+ 8. Termination.
413+
414+ You may not propagate or modify a covered work except as expressly
415+provided under this License. Any attempt otherwise to propagate or
416+modify it is void, and will automatically terminate your rights under
417+this License (including any patent licenses granted under the third
418+paragraph of section 11).
419+
420+ However, if you cease all violation of this License, then your
421+license from a particular copyright holder is reinstated (a)
422+provisionally, unless and until the copyright holder explicitly and
423+finally terminates your license, and (b) permanently, if the copyright
424+holder fails to notify you of the violation by some reasonable means
425+prior to 60 days after the cessation.
426+
427+ Moreover, your license from a particular copyright holder is
428+reinstated permanently if the copyright holder notifies you of the
429+violation by some reasonable means, this is the first time you have
430+received notice of violation of this License (for any work) from that
431+copyright holder, and you cure the violation prior to 30 days after
432+your receipt of the notice.
433+
434+ Termination of your rights under this section does not terminate the
435+licenses of parties who have received copies or rights from you under
436+this License. If your rights have been terminated and not permanently
437+reinstated, you do not qualify to receive new licenses for the same
438+material under section 10.
439+
440+ 9. Acceptance Not Required for Having Copies.
441+
442+ You are not required to accept this License in order to receive or
443+run a copy of the Program. Ancillary propagation of a covered work
444+occurring solely as a consequence of using peer-to-peer transmission
445+to receive a copy likewise does not require acceptance. However,
446+nothing other than this License grants you permission to propagate or
447+modify any covered work. These actions infringe copyright if you do
448+not accept this License. Therefore, by modifying or propagating a
449+covered work, you indicate your acceptance of this License to do so.
450+
451+ 10. Automatic Licensing of Downstream Recipients.
452+
453+ Each time you convey a covered work, the recipient automatically
454+receives a license from the original licensors, to run, modify and
455+propagate that work, subject to this License. You are not responsible
456+for enforcing compliance by third parties with this License.
457+
458+ An "entity transaction" is a transaction transferring control of an
459+organization, or substantially all assets of one, or subdividing an
460+organization, or merging organizations. If propagation of a covered
461+work results from an entity transaction, each party to that
462+transaction who receives a copy of the work also receives whatever
463+licenses to the work the party's predecessor in interest had or could
464+give under the previous paragraph, plus a right to possession of the
465+Corresponding Source of the work from the predecessor in interest, if
466+the predecessor has it or can get it with reasonable efforts.
467+
468+ You may not impose any further restrictions on the exercise of the
469+rights granted or affirmed under this License. For example, you may
470+not impose a license fee, royalty, or other charge for exercise of
471+rights granted under this License, and you may not initiate litigation
472+(including a cross-claim or counterclaim in a lawsuit) alleging that
473+any patent claim is infringed by making, using, selling, offering for
474+sale, or importing the Program or any portion of it.
475+
476+ 11. Patents.
477+
478+ A "contributor" is a copyright holder who authorizes use under this
479+License of the Program or a work on which the Program is based. The
480+work thus licensed is called the contributor's "contributor version".
481+
482+ A contributor's "essential patent claims" are all patent claims
483+owned or controlled by the contributor, whether already acquired or
484+hereafter acquired, that would be infringed by some manner, permitted
485+by this License, of making, using, or selling its contributor version,
486+but do not include claims that would be infringed only as a
487+consequence of further modification of the contributor version. For
488+purposes of this definition, "control" includes the right to grant
489+patent sublicenses in a manner consistent with the requirements of
490+this License.
491+
492+ Each contributor grants you a non-exclusive, worldwide, royalty-free
493+patent license under the contributor's essential patent claims, to
494+make, use, sell, offer for sale, import and otherwise run, modify and
495+propagate the contents of its contributor version.
496+
497+ In the following three paragraphs, a "patent license" is any express
498+agreement or commitment, however denominated, not to enforce a patent
499+(such as an express permission to practice a patent or covenant not to
500+sue for patent infringement). To "grant" such a patent license to a
501+party means to make such an agreement or commitment not to enforce a
502+patent against the party.
503+
504+ If you convey a covered work, knowingly relying on a patent license,
505+and the Corresponding Source of the work is not available for anyone
506+to copy, free of charge and under the terms of this License, through a
507+publicly available network server or other readily accessible means,
508+then you must either (1) cause the Corresponding Source to be so
509+available, or (2) arrange to deprive yourself of the benefit of the
510+patent license for this particular work, or (3) arrange, in a manner
511+consistent with the requirements of this License, to extend the patent
512+license to downstream recipients. "Knowingly relying" means you have
513+actual knowledge that, but for the patent license, your conveying the
514+covered work in a country, or your recipient's use of the covered work
515+in a country, would infringe one or more identifiable patents in that
516+country that you have reason to believe are valid.
517+
518+ If, pursuant to or in connection with a single transaction or
519+arrangement, you convey, or propagate by procuring conveyance of, a
520+covered work, and grant a patent license to some of the parties
521+receiving the covered work authorizing them to use, propagate, modify
522+or convey a specific copy of the covered work, then the patent license
523+you grant is automatically extended to all recipients of the covered
524+work and works based on it.
525+
526+ A patent license is "discriminatory" if it does not include within
527+the scope of its coverage, prohibits the exercise of, or is
528+conditioned on the non-exercise of one or more of the rights that are
529+specifically granted under this License. You may not convey a covered
530+work if you are a party to an arrangement with a third party that is
531+in the business of distributing software, under which you make payment
532+to the third party based on the extent of your activity of conveying
533+the work, and under which the third party grants, to any of the
534+parties who would receive the covered work from you, a discriminatory
535+patent license (a) in connection with copies of the covered work
536+conveyed by you (or copies made from those copies), or (b) primarily
537+for and in connection with specific products or compilations that
538+contain the covered work, unless you entered into that arrangement,
539+or that patent license was granted, prior to 28 March 2007.
540+
541+ Nothing in this License shall be construed as excluding or limiting
542+any implied license or other defenses to infringement that may
543+otherwise be available to you under applicable patent law.
544+
545+ 12. No Surrender of Others' Freedom.
546+
547+ If conditions are imposed on you (whether by court order, agreement or
548+otherwise) that contradict the conditions of this License, they do not
549+excuse you from the conditions of this License. If you cannot convey a
550+covered work so as to satisfy simultaneously your obligations under this
551+License and any other pertinent obligations, then as a consequence you may
552+not convey it at all. For example, if you agree to terms that obligate you
553+to collect a royalty for further conveying from those to whom you convey
554+the Program, the only way you could satisfy both those terms and this
555+License would be to refrain entirely from conveying the Program.
556+
557+ 13. Use with the GNU Affero General Public License.
558+
559+ Notwithstanding any other provision of this License, you have
560+permission to link or combine any covered work with a work licensed
561+under version 3 of the GNU Affero General Public License into a single
562+combined work, and to convey the resulting work. The terms of this
563+License will continue to apply to the part which is the covered work,
564+but the special requirements of the GNU Affero General Public License,
565+section 13, concerning interaction through a network will apply to the
566+combination as such.
567+
568+ 14. Revised Versions of this License.
569+
570+ The Free Software Foundation may publish revised and/or new versions of
571+the GNU General Public License from time to time. Such new versions will
572+be similar in spirit to the present version, but may differ in detail to
573+address new problems or concerns.
574+
575+ Each version is given a distinguishing version number. If the
576+Program specifies that a certain numbered version of the GNU General
577+Public License "or any later version" applies to it, you have the
578+option of following the terms and conditions either of that numbered
579+version or of any later version published by the Free Software
580+Foundation. If the Program does not specify a version number of the
581+GNU General Public License, you may choose any version ever published
582+by the Free Software Foundation.
583+
584+ If the Program specifies that a proxy can decide which future
585+versions of the GNU General Public License can be used, that proxy's
586+public statement of acceptance of a version permanently authorizes you
587+to choose that version for the Program.
588+
589+ Later license versions may give you additional or different
590+permissions. However, no additional obligations are imposed on any
591+author or copyright holder as a result of your choosing to follow a
592+later version.
593+
594+ 15. Disclaimer of Warranty.
595+
596+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
597+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
598+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
599+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
600+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
601+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
602+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
603+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
604+
605+ 16. Limitation of Liability.
606+
607+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
608+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
609+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
610+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
611+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
612+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
613+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
614+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
615+SUCH DAMAGES.
616+
617+ 17. Interpretation of Sections 15 and 16.
618+
619+ If the disclaimer of warranty and limitation of liability provided
620+above cannot be given local legal effect according to their terms,
621+reviewing courts shall apply local law that most closely approximates
622+an absolute waiver of all civil liability in connection with the
623+Program, unless a warranty or assumption of liability accompanies a
624+copy of the Program in return for a fee.
625+
626+ END OF TERMS AND CONDITIONS
627+
628+ How to Apply These Terms to Your New Programs
629+
630+ If you develop a new program, and you want it to be of the greatest
631+possible use to the public, the best way to achieve this is to make it
632+free software which everyone can redistribute and change under these terms.
633+
634+ To do so, attach the following notices to the program. It is safest
635+to attach them to the start of each source file to most effectively
636+state the exclusion of warranty; and each file should have at least
637+the "copyright" line and a pointer to where the full notice is found.
638+
639+ <one line to give the program's name and a brief idea of what it does.>
640+ Copyright (C) <year> <name of author>
641+
642+ This program is free software: you can redistribute it and/or modify
643+ it under the terms of the GNU General Public License as published by
644+ the Free Software Foundation, either version 3 of the License, or
645+ (at your option) any later version.
646+
647+ This program is distributed in the hope that it will be useful,
648+ but WITHOUT ANY WARRANTY; without even the implied warranty of
649+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
650+ GNU General Public License for more details.
651+
652+ You should have received a copy of the GNU General Public License
653+ along with this program. If not, see <http://www.gnu.org/licenses/>.
654+
655+Also add information on how to contact you by electronic and paper mail.
656+
657+ If the program does terminal interaction, make it output a short
658+notice like this when it starts in an interactive mode:
659+
660+ <program> Copyright (C) <year> <name of author>
661+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
662+ This is free software, and you are welcome to redistribute it
663+ under certain conditions; type `show c' for details.
664+
665+The hypothetical commands `show w' and `show c' should show the appropriate
666+parts of the General Public License. Of course, your program's commands
667+might be different; for a GUI interface, you would use an "about box".
668+
669+ You should also get your employer (if you work as a programmer) or school,
670+if any, to sign a "copyright disclaimer" for the program, if necessary.
671+For more information on this, and how to apply and follow the GNU GPL, see
672+<http://www.gnu.org/licenses/>.
673+
674+ The GNU General Public License does not permit incorporating your program
675+into proprietary programs. If your program is a subroutine library, you
676+may consider it more useful to permit linking proprietary applications with
677+the library. If this is what you want to do, use the GNU Lesser General
678+Public License instead of this License. But first, please read
679+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
680+
681
682=== added file 'COPYING.LESSER'
683--- COPYING.LESSER 1970-01-01 00:00:00 +0000
684+++ COPYING.LESSER 2009-07-13 15:53:45 +0000
685@@ -0,0 +1,165 @@
686+ GNU LESSER GENERAL PUBLIC LICENSE
687+ Version 3, 29 June 2007
688+
689+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
690+ Everyone is permitted to copy and distribute verbatim copies
691+ of this license document, but changing it is not allowed.
692+
693+
694+ This version of the GNU Lesser General Public License incorporates
695+the terms and conditions of version 3 of the GNU General Public
696+License, supplemented by the additional permissions listed below.
697+
698+ 0. Additional Definitions.
699+
700+ As used herein, "this License" refers to version 3 of the GNU Lesser
701+General Public License, and the "GNU GPL" refers to version 3 of the GNU
702+General Public License.
703+
704+ "The Library" refers to a covered work governed by this License,
705+other than an Application or a Combined Work as defined below.
706+
707+ An "Application" is any work that makes use of an interface provided
708+by the Library, but which is not otherwise based on the Library.
709+Defining a subclass of a class defined by the Library is deemed a mode
710+of using an interface provided by the Library.
711+
712+ A "Combined Work" is a work produced by combining or linking an
713+Application with the Library. The particular version of the Library
714+with which the Combined Work was made is also called the "Linked
715+Version".
716+
717+ The "Minimal Corresponding Source" for a Combined Work means the
718+Corresponding Source for the Combined Work, excluding any source code
719+for portions of the Combined Work that, considered in isolation, are
720+based on the Application, and not on the Linked Version.
721+
722+ The "Corresponding Application Code" for a Combined Work means the
723+object code and/or source code for the Application, including any data
724+and utility programs needed for reproducing the Combined Work from the
725+Application, but excluding the System Libraries of the Combined Work.
726+
727+ 1. Exception to Section 3 of the GNU GPL.
728+
729+ You may convey a covered work under sections 3 and 4 of this License
730+without being bound by section 3 of the GNU GPL.
731+
732+ 2. Conveying Modified Versions.
733+
734+ If you modify a copy of the Library, and, in your modifications, a
735+facility refers to a function or data to be supplied by an Application
736+that uses the facility (other than as an argument passed when the
737+facility is invoked), then you may convey a copy of the modified
738+version:
739+
740+ a) under this License, provided that you make a good faith effort to
741+ ensure that, in the event an Application does not supply the
742+ function or data, the facility still operates, and performs
743+ whatever part of its purpose remains meaningful, or
744+
745+ b) under the GNU GPL, with none of the additional permissions of
746+ this License applicable to that copy.
747+
748+ 3. Object Code Incorporating Material from Library Header Files.
749+
750+ The object code form of an Application may incorporate material from
751+a header file that is part of the Library. You may convey such object
752+code under terms of your choice, provided that, if the incorporated
753+material is not limited to numerical parameters, data structure
754+layouts and accessors, or small macros, inline functions and templates
755+(ten or fewer lines in length), you do both of the following:
756+
757+ a) Give prominent notice with each copy of the object code that the
758+ Library is used in it and that the Library and its use are
759+ covered by this License.
760+
761+ b) Accompany the object code with a copy of the GNU GPL and this license
762+ document.
763+
764+ 4. Combined Works.
765+
766+ You may convey a Combined Work under terms of your choice that,
767+taken together, effectively do not restrict modification of the
768+portions of the Library contained in the Combined Work and reverse
769+engineering for debugging such modifications, if you also do each of
770+the following:
771+
772+ a) Give prominent notice with each copy of the Combined Work that
773+ the Library is used in it and that the Library and its use are
774+ covered by this License.
775+
776+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
777+ document.
778+
779+ c) For a Combined Work that displays copyright notices during
780+ execution, include the copyright notice for the Library among
781+ these notices, as well as a reference directing the user to the
782+ copies of the GNU GPL and this license document.
783+
784+ d) Do one of the following:
785+
786+ 0) Convey the Minimal Corresponding Source under the terms of this
787+ License, and the Corresponding Application Code in a form
788+ suitable for, and under terms that permit, the user to
789+ recombine or relink the Application with a modified version of
790+ the Linked Version to produce a modified Combined Work, in the
791+ manner specified by section 6 of the GNU GPL for conveying
792+ Corresponding Source.
793+
794+ 1) Use a suitable shared library mechanism for linking with the
795+ Library. A suitable mechanism is one that (a) uses at run time
796+ a copy of the Library already present on the user's computer
797+ system, and (b) will operate properly with a modified version
798+ of the Library that is interface-compatible with the Linked
799+ Version.
800+
801+ e) Provide Installation Information, but only if you would otherwise
802+ be required to provide such information under section 6 of the
803+ GNU GPL, and only to the extent that such information is
804+ necessary to install and execute a modified version of the
805+ Combined Work produced by recombining or relinking the
806+ Application with a modified version of the Linked Version. (If
807+ you use option 4d0, the Installation Information must accompany
808+ the Minimal Corresponding Source and Corresponding Application
809+ Code. If you use option 4d1, you must provide the Installation
810+ Information in the manner specified by section 6 of the GNU GPL
811+ for conveying Corresponding Source.)
812+
813+ 5. Combined Libraries.
814+
815+ You may place library facilities that are a work based on the
816+Library side by side in a single library together with other library
817+facilities that are not Applications and are not covered by this
818+License, and convey such a combined library under terms of your
819+choice, if you do both of the following:
820+
821+ a) Accompany the combined library with a copy of the same work based
822+ on the Library, uncombined with any other library facilities,
823+ conveyed under the terms of this License.
824+
825+ b) Give prominent notice with the combined library that part of it
826+ is a work based on the Library, and explaining where to find the
827+ accompanying uncombined form of the same work.
828+
829+ 6. Revised Versions of the GNU Lesser General Public License.
830+
831+ The Free Software Foundation may publish revised and/or new versions
832+of the GNU Lesser General Public License from time to time. Such new
833+versions will be similar in spirit to the present version, but may
834+differ in detail to address new problems or concerns.
835+
836+ Each version is given a distinguishing version number. If the
837+Library as you received it specifies that a certain numbered version
838+of the GNU Lesser General Public License "or any later version"
839+applies to it, you have the option of following the terms and
840+conditions either of that published version or of any later version
841+published by the Free Software Foundation. If the Library as you
842+received it does not specify a version number of the GNU Lesser
843+General Public License, you may choose any version of the GNU Lesser
844+General Public License ever published by the Free Software Foundation.
845+
846+ If the Library as you received it specifies that a proxy can decide
847+whether future versions of the GNU Lesser General Public License shall
848+apply, that proxy's public statement of acceptance of any version is
849+permanent authorization for you to choose that version for the
850+Library.
851
852=== added file 'MANIFEST.in'
853--- MANIFEST.in 1970-01-01 00:00:00 +0000
854+++ MANIFEST.in 2009-08-26 21:18:02 +0000
855@@ -0,0 +1,13 @@
856+include COPYING COPYING.LESSER README
857+recursive-include data *.tmpl
858+include desktopcouch-pair.desktop.in
859+include po/POTFILES.in
860+include start-desktop-couchdb.sh
861+include stop-desktop-couchdb.sh
862+include desktopcouch/records/doc/records.txt
863+include bin/*
864+include docs/man/*
865+include MANIFEST.in MANIFEST
866+include org.desktopcouch.CouchDB.service
867+recursive-include contrib *.py
868+
869
870=== added file 'README'
871--- README 1970-01-01 00:00:00 +0000
872+++ README 2009-08-07 12:43:11 +0000
873@@ -0,0 +1,35 @@
874+This is Desktop Couch, an infrastructure to place a CouchDB on every desktop
875+and provide APIs and management tools for applications to store data within
876+it and share that data between computers and to the cloud.
877+
878+= Technical notes =
879+
880+== Creating databases, design documents, and views ==
881+
882+Desktop Couch will automatically create databases and design documents for you
883+on startup by inspecting the filesystem, meaning that you do not need to check
884+in your application whether your views exist. It is of course possible to create
885+views directly through the Records API, but having them created via the
886+filesystem allows managing of the view definitions more easily (they are
887+in separately editable files, which helps with version control) and packaging
888+(the files can be separately stored in a distribution package and installed
889+into the system-level XDG_DATA_DIR rather than the user-level folder).
890+
891+=== To create a database ===
892+
893+Create a file $XDG_DATA_DIR/desktop-couch/databases/YOUR_DB_NAME/database.cfg
894+
895+This file can currently be empty (in future it may contain database setup and
896+configuration information).
897+
898+=== To create a design document ===
899+
900+Create a file
901+$XDG_DATA_DIR/desktop-couch/databases/YOUR_DB_NAME/_design/DESIGN_DOC_NAME/views/VIEW_NAME/map.js
902+containing the map function from your view.
903+If you also require a reduce function for your view, create a file
904+$XDG_DATA_DIR/desktop-couch/databases/YOUR_DB_NAME/_design/DESIGN_DOC_NAME/views/VIEW_NAME/reduce.js.
905+
906+This is compatible with the filesystem view structure from CouchApp and
907+CouchDBKit.
908+
909
910=== added directory 'bin'
911=== added file 'bin/desktopcouch-pair'
912--- bin/desktopcouch-pair 1970-01-01 00:00:00 +0000
913+++ bin/desktopcouch-pair 2009-08-31 15:27:31 +0000
914@@ -0,0 +1,796 @@
915+#!/usr/bin/python
916+# Copyright 2009 Canonical Ltd.
917+#
918+# This file is part of desktopcouch.
919+#
920+# desktopcouch is free software: you can redistribute it and/or modify
921+# it under the terms of the GNU Lesser General Public License version 3
922+# as published by the Free Software Foundation.
923+#
924+# desktopcouch is distributed in the hope that it will be useful,
925+# but WITHOUT ANY WARRANTY; without even the implied warranty of
926+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
927+# GNU Lesser General Public License for more details.
928+#
929+# You should have received a copy of the GNU Lesser General Public License
930+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
931+# vim: filetype=python expandtab smarttab
932+
933+__doc__ = """\
934+A tool to aid two local machines to agree to perform some action, after
935+meatspace verification of identity. The action so far is to make two machines
936+replicate their couchdb instances to each other.
937+
938+Authentication
939+--------------
940+
941+One machine, Alice, sets herself to listen for invitations to pair with another
942+machine. In doing so, Alice is discoverable via Zeroconf on local network.
943+
944+Another machine, Bob, sees the advertisement and generates a secret message and
945+a public seed. Bob then computes the SHA512 digest of the secret, and sends an
946+invitation to Alice, in the form of the hex digest concatenated with the public
947+seed. Bob displays the secret to the user, who walks the secret over to Alice.
948+
949+Alice then computes the SHA512 digest of Bob's secret and compares it to be
950+sure that the other machine is indeed the user's. Alice then concatenates
951+Bob's secret and the public seed, and sends the resulting hex digest back to
952+Bob to prove that she received the secret from the user. Alice sets herself to
953+replicate to Bob.
954+
955+Bob computes the secret+publicseed digest and compares it with the received hex
956+digest from Alice. When it matches, he sets himself to replicate to Alice.
957+"""
958+
959+
960+
961+import logging
962+import getpass
963+import gettext
964+# gettext implements "_" function. pylint: disable-msg=E0602
965+import random
966+import cgi
967+
968+from twisted.internet import gtk2reactor
969+gtk2reactor.install()
970+from twisted.internet.reactor import run as run_program
971+from twisted.internet.reactor import stop as stop_program
972+
973+import pygtk
974+pygtk.require('2.0')
975+import gtk
976+import gobject
977+import pango
978+
979+from desktopcouch.pair.couchdb_pairing import network_io
980+from desktopcouch.pair.couchdb_pairing import dbus_io
981+from desktopcouch.pair import pairing_record_type
982+
983+discovery_tool_version = "1"
984+
985+CLOUD_SERVICES = {}
986+
987+def generate_secret(length=7):
988+ """Create a secret that is easy to write and read. We hate ambiguity and
989+ errors."""
990+
991+ pool = "abcdefghijklmnopqrstuvwxyz23456789#$%&*+=-"
992+ return unmap_easily_mistaken(
993+ "".join(random.choice(pool) for n in range(length)))
994+
995+def unmap_easily_mistaken(user_input):
996+ """Returns ASCII-encoded text with visually-ambiguous characters crushed
997+ down to some common atom."""
998+
999+ import string
1000+ easily_mistaken = string.maketrans("!10@", "lloo")
1001+ return string.translate(user_input.lower().encode("ascii"), easily_mistaken)
1002+
1003+def get_host_info():
1004+ """Create some text that hopefully identifies this host out of many."""
1005+
1006+ import platform
1007+
1008+ try:
1009+ uptime_seconds = int(float(file("/proc/uptime").read().split()[0]))
1010+ days, uptime_seconds = divmod(uptime_seconds, 60*60*24)
1011+ hours, uptime_seconds = divmod(uptime_seconds, 60*60)
1012+ minutes, seconds = divmod(uptime_seconds, 60)
1013+
1014+ # Is ISO8601 too nerdy? ...
1015+ #uptime_descr = ", up PT%(days)dD%(hours)dH%(minutes)dM" % locals()
1016+ uptime_descr = ", up %(days)dd %(hours)dh%(minutes)dm" % locals()
1017+ except OSError:
1018+ uptime_descr = ""
1019+
1020+ try:
1021+ return " ".join(platform.dist()) + uptime_descr
1022+ except AttributeError:
1023+ return platform.platform() + uptime_descr
1024+
1025+
1026+class Inviting:
1027+ """We're part of "Bob" in the module's story.
1028+
1029+ We see listeners on the network and send invitations to pair with us.
1030+ We generate a secret message and a public seed. We get the SHA512 hex
1031+ digest of the secret message, append the public seed and send it to
1032+ Alice. We also display the cleartext of the secret message to the
1033+ screen, so that the user can take it to the machine he thinks is Alice.
1034+
1035+ Eventually, we receive a message back from Alice. We compute the
1036+ secret message we started with concatenated with the public seed, and
1037+ if that matches Alice's message, then Alice must know the secret we
1038+ displayed to the user. We then set outselves to replicate to Alice."""
1039+
1040+ def delete_event(self, widget, event, data=None):
1041+ """User requested window be closed. False to propogate event."""
1042+ return False
1043+
1044+ def destroy(self, widget, data=None):
1045+ """The window is destroyed."""
1046+ self.inviter.close()
1047+
1048+ def auth_completed(self, remote_host, remote_port, remote_info):
1049+ """The auth stage is finished. Now pair with the remote host."""
1050+ pair_with_host(remote_host, remote_port, remote_info)
1051+ self.window.destroy()
1052+
1053+ def on_close(self):
1054+ """When a socket is closed, we should stop inviting. (?)"""
1055+ self.window.destroy()
1056+
1057+ def __init__(self, service, hostname, port):
1058+ self.logging = logging.getLogger(self.__class__.__name__)
1059+
1060+ self.hostname = hostname
1061+ self.port = port
1062+
1063+ self.window = gtk.Window()
1064+ self.window.set_border_width(6)
1065+ self.window.connect("delete_event", self.delete_event)
1066+ self.window.connect("destroy", self.destroy)
1067+ self.window.set_destroy_with_parent(True)
1068+ self.window.set_title(
1069+ _("Inviting %s to pair for CouchDB Pairing") % hostname)
1070+
1071+ secret_message = generate_secret()
1072+ self.secret_message = secret_message
1073+ self.public_seed = generate_secret()
1074+
1075+ self.inviter = network_io.start_send_invitation(hostname, port,
1076+ self.auth_completed, self.secret_message, self.public_seed,
1077+ self.on_close)
1078+
1079+ top_vbox = gtk.VBox()
1080+ self.window.add(top_vbox)
1081+
1082+ text = gtk.Label()
1083+ text.set_markup(_("""We're inviting %s to pair with\n""" +
1084+ """us, and to prove veracity of the invitation we\n""" +
1085+ """sent, it is waiting for you to tell it this secret:\n""" +
1086+ """<span font-size="xx-large" color="blue" weight="bold">""" +
1087+ """<tt>%s</tt></span> .""") %
1088+ (cgi.escape(service), cgi.escape(self.secret_message)))
1089+ text.set_justify(gtk.JUSTIFY_CENTER)
1090+ top_vbox.pack_start(text, False, False, 10)
1091+ text.show()
1092+
1093+ cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL)
1094+ cancel_button.set_border_width(3)
1095+ cancel_button.connect("clicked", lambda widget: self.window.destroy())
1096+ top_vbox.pack_end(cancel_button, False, False, 10)
1097+ cancel_button.show()
1098+
1099+ self.window.show_all()
1100+
1101+
1102+class AcceptInvitation:
1103+ """We're part of 'Alice' in this module's story.
1104+
1105+ We've received an invitation. We now send the other end a secret key. The
1106+ secret should make its way back to us via meatspace. We open a dialog
1107+ asking for that secret here, which we validate.
1108+
1109+ When we validate it, we add this end as replicating to the other end. The
1110+ other end should also set itself to replicate to us."""
1111+
1112+ def delete_event(self, widget, event, data=None):
1113+ """User requested window be closed. False to propogate event."""
1114+ return False
1115+
1116+ def destroy(self, widget, data=None):
1117+ """Window is destroyed."""
1118+ pass
1119+
1120+ def on_close(self):
1121+ """Handle communication channel being closed."""
1122+ # FIXME this is unimplemented and unused.
1123+ self.destroy()
1124+
1125+ def __init__(self, remote_host, is_secret_valid, send_valid_key):
1126+ self.logging = logging.getLogger(self.__class__.__name__)
1127+
1128+ self.is_secret_valid = is_secret_valid
1129+ self.send_valid_key = send_valid_key
1130+
1131+ self.window = gtk.Window()
1132+ self.window.set_border_width(6)
1133+
1134+ self.logging.info("want to listen for invitations.")
1135+
1136+ self.window.connect("delete_event", self.delete_event)
1137+ self.window.connect("destroy", self.destroy)
1138+ self.window.set_destroy_with_parent(True)
1139+ self.window.set_title(_("Accepting Invitation"))
1140+
1141+ top_vbox = gtk.VBox()
1142+ top_vbox.show()
1143+ self.window.add(top_vbox)
1144+
1145+ self.remote_hostname = dbus_io.get_remote_hostname(remote_host)
1146+
1147+ description = gtk.Label(
1148+ _("To verify your pairing with %s, enter its secret.") %
1149+ self.remote_hostname)
1150+ description.show()
1151+ top_vbox.pack_start(description, False, False, 0)
1152+
1153+ self.entry_box = gtk.Entry(18)
1154+ self.entry_box.connect("activate", lambda widget: self.verify_secret())
1155+ #self.window.connect("activate", lambda widget: self.verify_secret())
1156+ self.entry_box.set_activates_default(True)
1157+ self.entry_box.show()
1158+ top_vbox.pack_start(self.entry_box, False, False, 0)
1159+
1160+ self.result = gtk.Label("")
1161+ self.result.show()
1162+ self.entry_box.connect("changed",
1163+ lambda widget: self.result.set_text(""))
1164+ top_vbox.pack_start(self.result, False, False, 0)
1165+
1166+ button_bar = gtk.HBox(homogeneous=True)
1167+ button_bar.show()
1168+ top_vbox.pack_end(button_bar, False, False, 10)
1169+
1170+ cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL)
1171+ cancel_button.set_border_width(3)
1172+ cancel_button.connect("clicked", lambda widget: self.window.destroy())
1173+ button_bar.pack_end(cancel_button, False, False, 10)
1174+ cancel_button.show()
1175+
1176+ connect_button = gtk.Button(_("Verify and connect"))
1177+ add_image = gtk.Image()
1178+ add_image.set_from_stock(gtk.STOCK_CONNECT, gtk.ICON_SIZE_BUTTON)
1179+ connect_button.set_image(add_image)
1180+ connect_button.set_border_width(3)
1181+ connect_button.connect("clicked", lambda widget: self.verify_secret())
1182+ button_bar.pack_end(connect_button, False, False, 10)
1183+ connect_button.show()
1184+
1185+ self.window.show_all()
1186+
1187+ def verify_secret(self):
1188+ """We got a sumbission from the user's fingers as to what he thinks
1189+ the secret is. We verify it, and if it's what the other end started
1190+ with, then it's okay to let us pair with it."""
1191+
1192+ proposed_secret = unmap_easily_mistaken(self.entry_box.get_text())
1193+ if self.is_secret_valid(proposed_secret):
1194+ pair_with_host(self.remote_hostname, "(port)", "(info)")
1195+ self.send_valid_key(proposed_secret)
1196+ self.window.destroy()
1197+ else:
1198+ self.result.set_text("sorry, that is wrong")
1199+
1200+
1201+class Listening:
1202+ """We're part of 'Alice' in this module's story.
1203+
1204+ Window that starts listening for other machines to pick *us* to pair
1205+ with. There must be at least one of these on the network for pairing to
1206+ happen. We listen for a finite amount of time, and then stop."""
1207+
1208+ def delete_event(self, widget, event, data=None):
1209+ """User requested window be closed. False to propogate event."""
1210+ return False
1211+
1212+ def destroy(self, widget, data=None):
1213+ """Window is destroyed."""
1214+ self.timeout_counter = None
1215+
1216+ if self.advertisement is not None:
1217+ self.advertisement.die()
1218+ self.listener.close()
1219+
1220+ def receive_invitation_challenge(self, remote_address, is_secret_valid,
1221+ send_secret):
1222+ """When we receive an invitation, check its validity and if
1223+ it's what we expected, then continue and accept it."""
1224+
1225+ self.logging.warn("received invitation from %s", remote_address)
1226+ self.acceptor = AcceptInvitation(remote_address, is_secret_valid,
1227+ send_secret)
1228+ self.acceptor.window.connect("destroy",
1229+ lambda *args: setattr(self, "acceptor", None) and False)
1230+
1231+ def cancel_acceptor(self):
1232+ """Destroy window when connection canceled."""
1233+ self.acceptor.window.destroy()
1234+
1235+ def make_listener(self, couchdb_instance):
1236+ """Start listening for connections, and start advertising that
1237+ we're listening."""
1238+
1239+ self.listener = network_io.ListenForInvitations(
1240+ self.receive_invitation_challenge,
1241+ lambda: self.window.destroy())
1242+
1243+ listen_port = self.listener.get_local_port()
1244+
1245+ hostname, domainname = dbus_io.get_local_hostname()
1246+ username = getpass.getuser()
1247+ self.advertisement = dbus_io.PairAdvertisement(port=listen_port,
1248+ name="%s-%s-%d" % (hostname, username, listen_port),
1249+ text=dict(version=str(discovery_tool_version),
1250+ description=get_host_info()))
1251+ self.advertisement.publish()
1252+ return hostname, username, listen_port
1253+
1254+ def __init__(self, couchdb_instance):
1255+ self.logging = logging.getLogger(self.__class__.__name__)
1256+
1257+ self.listener = None
1258+ self.listener_loop = None
1259+ self.advertisement = None
1260+ self.acceptor = None
1261+
1262+ self.timeout_counter = 180
1263+
1264+ self.window = gtk.Window()
1265+ self.window.set_border_width(6)
1266+
1267+ self.logging.info("want to listen for invitations.")
1268+
1269+ self.window.connect("delete_event", self.delete_event)
1270+ self.window.connect("destroy", self.destroy)
1271+ self.window.set_destroy_with_parent(True)
1272+ self.window.set_title(_("Waiting for CouchDB Pairing Invitations"))
1273+
1274+ top_vbox = gtk.VBox()
1275+ top_vbox.show()
1276+ self.window.add(top_vbox)
1277+
1278+ self.counter_text = gtk.Label("#")
1279+ self.counter_text.show()
1280+
1281+ top_vbox.pack_end(self.counter_text, False, False, 5)
1282+
1283+ button_bar = gtk.HBox(homogeneous=True)
1284+ button_bar.show()
1285+ top_vbox.pack_end(button_bar, False, False, 10)
1286+
1287+ cancel_button = gtk.Button(stock=gtk.STOCK_CANCEL)
1288+ cancel_button.set_border_width(3)
1289+ cancel_button.connect("clicked", lambda *args: self.window.destroy())
1290+ button_bar.pack_end(cancel_button, False, False, 10)
1291+ cancel_button.show()
1292+
1293+ add_minute_button = gtk.Button(_("Add 60 seconds"))
1294+ add_image = gtk.Image()
1295+ add_image.set_from_stock(gtk.STOCK_ADD, gtk.ICON_SIZE_BUTTON)
1296+ add_minute_button.set_image(add_image)
1297+ add_minute_button.set_border_width(3)
1298+ add_minute_button.connect("clicked",
1299+ lambda widget: self.add_to_timeout_counter(60))
1300+ button_bar.pack_end(add_minute_button, False, False, 10)
1301+ add_minute_button.show()
1302+
1303+ hostid, userid, listen_port = self.make_listener(couchdb_instance)
1304+
1305+ text = gtk.Label()
1306+ text.set_markup(
1307+ _("""We're listening for invitations! From another\n""" +
1308+ """machine on this local network, run this\n""" +
1309+ """same tool and find the machine called\n""" +
1310+ """<span font-size="xx-large" weight="bold"><tt>""" +
1311+ """%s-%s-%d</tt></span> .""") %
1312+ (cgi.escape(hostid), cgi.escape(userid),
1313+ listen_port))
1314+ text.set_justify(gtk.JUSTIFY_CENTER)
1315+ top_vbox.pack_start(text, False, False, 10)
1316+ text.show()
1317+
1318+ self.update_counter_view()
1319+ self.window.show_all()
1320+
1321+ gobject.timeout_add(1000, self.decrement_counter)
1322+
1323+ def add_to_timeout_counter(self, seconds):
1324+ """The user wants more time. Add seconds to the clock."""
1325+ self.timeout_counter += seconds
1326+ self.update_counter_view()
1327+
1328+ def update_counter_view(self):
1329+ """Update the counter widget with pretty text."""
1330+ self.counter_text.set_text(
1331+ _("%d seconds remaining") % self.timeout_counter)
1332+
1333+ def decrement_counter(self):
1334+ """Tick! Decrement the counter and update the display."""
1335+ if self.timeout_counter is None:
1336+ return False
1337+
1338+ self.timeout_counter -= 1
1339+ if self.timeout_counter < 0:
1340+ self.window.destroy()
1341+ return False
1342+
1343+ self.update_counter_view()
1344+ return True
1345+
1346+
1347+class PickOrListen:
1348+ """Main top-level window that represents the life of the application."""
1349+
1350+ def delete_event(self, widget, event, data=None):
1351+ """User requested window be closed. False to propogate event."""
1352+ return False
1353+
1354+ def destroy(self, widget, data=None):
1355+ """The window was destroyed."""
1356+ stop_program()
1357+
1358+ def create_pick_pane(self, container):
1359+ """Set up the pane that contains what's necessary to choose an
1360+ already-listening tool instance. This sets up a "Bob" in the
1361+ module's story."""
1362+
1363+ # positions: host id, description, pair host, pair port, is_cloud
1364+ listening_hosts = gtk.TreeStore(str, str, str, int, bool)
1365+
1366+ # If there is an Ubuntu One key in the keyring, add Ubuntu One
1367+ # as an item to be paired with
1368+ import gnomekeyring
1369+ try:
1370+ matches = gnomekeyring.find_items_sync(
1371+ gnomekeyring.ITEM_GENERIC_SECRET,
1372+ {'ubuntuone-realm': "https://ubuntuone.com",
1373+ 'oauth-consumer-key': "ubuntuone"})
1374+ except gnomekeyring.NoMatchError:
1375+ matches = None
1376+ if matches:
1377+ # parse "a=b&c=d" to {"a":"b","c":"d"}
1378+ oauth_data = dict([x.split("=", 1) for x in
1379+ matches[0].secret.split("&")])
1380+ oauth_data.update({
1381+ "consumer_key": "ubuntuone",
1382+ "consumer_secret": "",
1383+ })
1384+ listening_hosts.append(None, ["Ubuntu One", "The Ubuntu One cloud service",
1385+ "ubuntuone.com", 5984, True])
1386+ CLOUD_SERVICES["Ubuntu One"] = oauth_data
1387+
1388+ self.inviting = None # pylint: disable-msg=W0201
1389+
1390+ hostid_col = gtk.TreeViewColumn(_("service name"))
1391+ description_col = gtk.TreeViewColumn(_("service name"))
1392+
1393+ pick_box = gtk.VBox()
1394+ container.pack_start(pick_box, False, False, 10)
1395+
1396+ l = gtk.Label(_("Pick a listening host to invite it to pair with us."))
1397+ pick_box.pack_start(l, False, False, 0)
1398+ l.show()
1399+
1400+ tv = gtk.TreeView(listening_hosts)
1401+ tv.set_headers_visible(False)
1402+ tv.set_rules_hint(True)
1403+ tv.show()
1404+
1405+ def clicked(selection):
1406+ """An item in the list of services was clicked, so now we go
1407+ about inviting it to pair with us."""
1408+
1409+ model, iter = selection.get_selected()
1410+ if not iter:
1411+ return
1412+ service = model.get_value(iter, 0)
1413+ hostname = model.get_value(iter, 2)
1414+ port = model.get_value(iter, 3)
1415+ is_cloud = model.get_value(iter, 4)
1416+
1417+ if is_cloud:
1418+ # Pairing with a cloud service, which doesn't do key exchange
1419+ pair_with_cloud_service(service, hostname, port)
1420+ return
1421+
1422+
1423+ self.logging.error("Local pairing is not yet supported. Aborting.")
1424+ fail_note = gtk.MessageDialog(
1425+ parent=pick_or_listen.window,
1426+ flags=gtk.DIALOG_DESTROY_WITH_PARENT,
1427+ buttons=gtk.BUTTONS_OK,
1428+ type=gtk.MESSAGE_ERROR,
1429+ message_format =_("Sorry, couchdb authentication is not yet enabled, so local pairing is not supported"))
1430+ fail_note.run()
1431+ fail_note.destroy()
1432+ return False
1433+
1434+
1435+ self.logging.info("connecting to %s:%s tcp to invite",
1436+ hostname, port)
1437+ if self.inviting != None:
1438+ self.inviting.window.destroy()
1439+ self.inviting = Inviting(service, hostname, port)
1440+ self.inviting.window.connect("destroy",
1441+ lambda *args: setattr(self, "inviting_window", None))
1442+
1443+ tv_selection = tv.get_selection()
1444+ tv_selection.connect("changed", clicked)
1445+
1446+ scrolled_window = gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
1447+ scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
1448+ scrolled_window.set_border_width(10)
1449+ scrolled_window.add_with_viewport(tv)
1450+ scrolled_window.show()
1451+
1452+ pick_box.pack_start(scrolled_window, True, False, 0)
1453+
1454+ def add_service_to_list(name, description, host, port, version):
1455+ """When a zeroconf service appears, this adds it to the
1456+ listing of choices."""
1457+
1458+ listening_hosts.append(None, [name, description, host, port, False, None])
1459+
1460+ def remove_service_from_list(name):
1461+ """When a zeroconf service disappears, this finds it in the
1462+ listing and removes it as an option for picking."""
1463+
1464+ it = listening_hosts.get_iter_first()
1465+ while it is not None:
1466+ if listening_hosts.get_value(it, 0) == name:
1467+ listening_hosts.remove(it)
1468+ return True
1469+ it = listening_hosts.iter_next(it)
1470+
1471+ dbus_io.discover_services(add_service_to_list, remove_service_from_list)
1472+
1473+ cell = gtk.CellRendererText()
1474+ cell.set_property("weight", pango.WEIGHT_BOLD)
1475+ cell.set_property("weight-set", True)
1476+ tv.append_column(hostid_col)
1477+ hostid_col.pack_start(cell, True)
1478+ hostid_col.add_attribute(cell, 'text', 0)
1479+
1480+ cell = gtk.CellRendererText()
1481+ cell.set_property("ellipsize", pango.ELLIPSIZE_END)
1482+ cell.set_property("ellipsize-set", True)
1483+ tv.append_column(description_col)
1484+ description_col.pack_start(cell, True)
1485+ description_col.add_attribute(cell, 'text', 1)
1486+
1487+ return pick_box
1488+
1489+
1490+ def create_single_listen_pane(self, container):
1491+ """This sets up an "Alice" from the module's story.
1492+
1493+ This assumes we're pairing a single, known local CouchDB instance,
1494+ instead of generic instances that we'd need more information to talk
1495+ about. Instead of using this function, one might use another that
1496+ lists local DBs as a way of picking one to pair. This function assumes
1497+ we know the answer to that."""
1498+
1499+ def listen(btn, couchdb_instance=None):
1500+ """When we decide to listen for invitations, this spawns the
1501+ advertising/information window, and disables the button that
1502+ causes/-ed us to get here (to prevent multiple instances)."""
1503+
1504+ if couchdb_instance is None:
1505+ # assume local for this user. FIXME
1506+ pass
1507+
1508+
1509+ self.logging.error("Local pairing is not yet supported. Aborting.")
1510+ fail_note = gtk.MessageDialog(
1511+ parent=pick_or_listen.window,
1512+ flags=gtk.DIALOG_DESTROY_WITH_PARENT,
1513+ buttons=gtk.BUTTONS_OK,
1514+ type=gtk.MESSAGE_ERROR,
1515+ message_format =_("Sorry, couchdb authentication is not yet enabled, so local pairing is not supported"))
1516+ fail_note.run()
1517+ fail_note.destroy()
1518+ return False
1519+
1520+
1521+ btn.set_sensitive(False)
1522+ listening = Listening(couchdb_instance)
1523+ listening.window.connect("destroy",
1524+ lambda w: btn.set_sensitive(True))
1525+
1526+ padding = 6
1527+
1528+ listen_box = gtk.HBox()
1529+ container.pack_start(listen_box, False, False, 10)
1530+
1531+ l = gtk.Label(_("Add this host to the list for others to see?"))
1532+ listen_box.pack_start(l, True, False, padding)
1533+ l.show()
1534+
1535+ listen_button = gtk.Button(_("Listen for invitations"))
1536+ listen_button.connect("clicked", listen, None)
1537+ listen_box.pack_start(listen_button, True, False, padding)
1538+ listen_button.show()
1539+
1540+ return listen_box
1541+
1542+ def create_any_listen_pane(self, container):
1543+ """Unused. An example of where to start when we don't already have
1544+ a couchdb instance in mind to advertise. This should be the generic
1545+ version."""
1546+
1547+ l = gtk.Label(_("I also know of CouchDB sessions here. Pick one " +
1548+ "to add it to the invitation list for other computers to see."))
1549+
1550+ local_sharables_list = gtk.TreeStore(str, str)
1551+ # et c, et c
1552+ #some_row_in_list.connect("clicked", self.listen, target_db_info)
1553+
1554+ def __init__(self):
1555+ self.logging = logging.getLogger(self.__class__.__name__)
1556+
1557+ self.window = gtk.Window()
1558+
1559+ self.window.connect("delete_event", self.delete_event)
1560+ self.window.connect("destroy", self.destroy)
1561+
1562+ self.window.set_border_width(8)
1563+ self.window.set_title(_("CouchDB Pairing Tool"))
1564+
1565+ top_vbox = gtk.VBox()
1566+ self.window.add(top_vbox)
1567+
1568+ self.pick_pane = self.create_pick_pane(top_vbox)
1569+ self.listen_pane = self.create_single_listen_pane(top_vbox)
1570+
1571+ copyright = gtk.Label(_("Copyright 2009 Canonical"))
1572+ top_vbox.pack_end(copyright, False, False, 0)
1573+ copyright.show()
1574+
1575+ self.pick_pane.show()
1576+ self.listen_pane.show()
1577+
1578+ top_vbox.show()
1579+ self.window.show()
1580+
1581+
1582+def pair_with_host(host, port, info):
1583+ """We've verified all is correct and authorized, so now we pair
1584+ the databases."""
1585+ logging.info("verified host %s/%s/%s. Done!", host, port, info)
1586+
1587+ # Some kind of two-phase commit would be nice here, before we say
1588+ # successful.
1589+ #couchdb_io.replicate_to(...)
1590+
1591+ success_note = gtk.Dialog(title=_("Paired with %(host)s") % locals(),
1592+ parent=pick_or_listen.window,
1593+ flags=gtk.DIALOG_DESTROY_WITH_PARENT,
1594+ buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK,))
1595+ text = gtk.Label(
1596+ _("Successfully paired with %(host)s %(info)s.") % locals())
1597+ text.show()
1598+ content_box = success_note.get_content_area()
1599+ content_box.pack_start(text, True, True, 20)
1600+ success_note.connect("close",
1601+ lambda *args: pick_or_listen.window.destroy())
1602+ success_note.connect("response",
1603+ lambda *args: pick_or_listen.window.destroy())
1604+ success_note.show()
1605+
1606+def pair_with_cloud_service(name, hostname, port):
1607+ """Write a paired server record for the selected cloud service."""
1608+ from desktopcouch.records.server import CouchDatabase
1609+ from desktopcouch.records.record import Record
1610+ import uuid
1611+
1612+ # Create a paired server record
1613+ service_data = CLOUD_SERVICES[name]
1614+ data = {
1615+ "record_type": pairing_record_type,
1616+ "pairing_identifier": str(uuid.uuid4()),
1617+ "server": "%s:%s" % (hostname, port),
1618+ "oauth": {
1619+ "consumer_key": service_data["consumer_key"],
1620+ "consumer_secret": service_data["consumer_secret"],
1621+ "token": service_data["oauth_token"],
1622+ "token_secret": service_data["oauth_token_secret"],
1623+ },
1624+ "pull_from_server": True
1625+ }
1626+ try:
1627+ d = CouchDatabase("management", create=True)
1628+ r = Record(data)
1629+ record_id = d.put_record(r)
1630+ except Exception, e:
1631+ fail_note = gtk.MessageDialog(
1632+ parent=pick_or_listen.window,
1633+ flags=gtk.DIALOG_DESTROY_WITH_PARENT,
1634+ buttons=gtk.BUTTONS_OK,
1635+ type=gtk.MESSAGE_ERROR,
1636+ message_format =_("Couldn't save pairing details for %s") % name)
1637+ fail_note.run()
1638+ logging.exception(e)
1639+ fail_note.destroy()
1640+ return
1641+
1642+ success_note = gtk.MessageDialog(
1643+ parent=pick_or_listen.window,
1644+ flags=gtk.DIALOG_DESTROY_WITH_PARENT,
1645+ buttons=gtk.BUTTONS_OK,
1646+ type=gtk.MESSAGE_INFO,
1647+ message_format =_("Successfully paired with %s") % name)
1648+ success_note.run()
1649+ success_note.destroy()
1650+
1651+
1652+def set_couchdb_bind_address():
1653+ from desktopcouch.records.server import CouchDatabase
1654+ from desktopcouch import local_files
1655+ bind_address = local_files.get_bind_address()
1656+
1657+ if bind_address not in ("127.0.0.1", "0.0.0.0", "::1", None):
1658+ logging.info("we're not qualified to change explicit address %s",
1659+ bind_address)
1660+ return False
1661+
1662+ db = CouchDatabase("management", create=True)
1663+ results = db.get_records(create_view=True)
1664+ count = 0
1665+ for row in results[pairing_record_type]:
1666+ if "server" in row.value and row.value["server"] != "":
1667+ # Is the record of something that probably connects back to us?
1668+ logging.debug("not counting fully-addressed machine %r", row.value["server"])
1669+ continue
1670+ count += 1
1671+ logging.debug("paired machine count is %d", count)
1672+ if count > 0:
1673+ if ":" in bind_address:
1674+ want_bind_address = "::0"
1675+ else:
1676+ want_bind_address = "0.0.0.0"
1677+ else:
1678+ if ":" in bind_address:
1679+ want_bind_address = "::0"
1680+ else:
1681+ want_bind_address = "127.0.0.1"
1682+
1683+ if bind_address != want_bind_address:
1684+ local_files.set_bind_address(want_bind_address)
1685+ logging.warning("changing the desktopcouch bind address from %r to %r",
1686+ bind_address, want_bind_address)
1687+
1688+def main(args):
1689+ """Start execution."""
1690+ global pick_or_listen # pylint: disable-msg=W0601
1691+
1692+ logging.basicConfig(level=logging.DEBUG, format=
1693+ "%(asctime)s [%(process)d] %(name)s:%(levelname)s: %(message)s")
1694+
1695+ gettext.install("couchdb_pairing")
1696+
1697+ try:
1698+ logging.debug("starting couchdb pairing tool")
1699+ pick_or_listen = PickOrListen()
1700+ return run_program()
1701+ finally:
1702+ set_couchdb_bind_address()
1703+ logging.debug("exiting couchdb pairing tool")
1704+
1705+
1706+if __name__ == "__main__":
1707+ import sys
1708+ import desktopcouch
1709+ desktopcouch_port = desktopcouch.find_port()
1710+ main(sys.argv)
1711
1712=== added file 'bin/desktopcouch-paired-replication-manager'
1713--- bin/desktopcouch-paired-replication-manager 1970-01-01 00:00:00 +0000
1714+++ bin/desktopcouch-paired-replication-manager 2009-08-30 12:25:52 +0000
1715@@ -0,0 +1,151 @@
1716+#!/bin/sh
1717+""""exec ${PYTHON:-python} -t $0 "$@";" """
1718+# vim: filetype=python expandtab smarttab
1719+
1720+# Copyright 2009 Canonical Ltd.
1721+#
1722+# This file is part of desktopcouch.
1723+#
1724+# desktopcouch is free software: you can redistribute it and/or modify
1725+# it under the terms of the GNU Lesser General Public License version 3
1726+# as published by the Free Software Foundation.
1727+#
1728+# desktopcouch is distributed in the hope that it will be useful,
1729+# but WITHOUT ANY WARRANTY; without even the implied warranty of
1730+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1731+# GNU Lesser General Public License for more details.
1732+#
1733+# You should have received a copy of the GNU Lesser General Public License
1734+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
1735+#
1736+# Authors: Chad Miller <chad.miller@canonical.com>
1737+
1738+import os
1739+import threading
1740+import logging
1741+import logging.handlers
1742+log = logging.getLogger("main")
1743+
1744+from twisted.internet import gtk2reactor
1745+gtk2reactor.install()
1746+from twisted.internet import reactor, task
1747+import xdg.BaseDirectory
1748+
1749+import desktopcouch
1750+from desktopcouch import local_files
1751+from desktopcouch.pair.couchdb_pairing import couchdb_io
1752+from desktopcouch.pair.couchdb_pairing import dbus_io
1753+
1754+already_replicating = False
1755+
1756+class ReplicatorThread(threading.Thread):
1757+ def __init__(self, local_port):
1758+ log.debug("starting up replication thread")
1759+ super(ReplicatorThread, self).__init__()
1760+ self.local_port = local_port
1761+
1762+ def run(self):
1763+ global already_replicating # Fuzzy, as not really critical,
1764+ already_replicating = True # just trying to be polite.
1765+ try:
1766+ for uuid, addr, port in dbus_io.get_seen_paired_hosts():
1767+ log.debug("host %s is seen; want to replicate to it", uuid)
1768+ for db_name in couchdb_io.get_database_names_replicatable():
1769+ couchdb_io.replicate(db_name, db_name,
1770+ target_host=addr, target_port=port,
1771+ source_port=self.local_port)
1772+
1773+
1774+ # TODO: get static addressed paired hosts and replicate to
1775+ # those too.
1776+
1777+ finally:
1778+ already_replicating = False
1779+ log.debug("finished replicating")
1780+
1781+
1782+def replicate_local_databases_to_paired_hosts(local_port):
1783+ if already_replicating:
1784+ log.warn("haven't finished replicating before next time to start.")
1785+ return False
1786+
1787+ r = ReplicatorThread(local_port)
1788+ r.start()
1789+
1790+def main(args):
1791+ log_directory = os.path.join(xdg.BaseDirectory.xdg_cache_home,
1792+ "ubuntuone/log")
1793+ try:
1794+ os.makedirs(log_directory)
1795+ except:
1796+ pass
1797+ rotating_log = logging.handlers.TimedRotatingFileHandler(
1798+ os.path.join(log_directory, "desktop-couch-replication.log"),
1799+ "midnight", 1, 14)
1800+ rotating_log.setLevel(logging.DEBUG)
1801+ formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
1802+ rotating_log.setFormatter(formatter)
1803+ console = logging.StreamHandler()
1804+ console.setLevel(logging.WARNING)
1805+ logging.getLogger('').addHandler(rotating_log)
1806+ logging.getLogger('').addHandler(console)
1807+ logging.getLogger('').setLevel(logging.DEBUG)
1808+
1809+ try:
1810+ log.info("Starting.")
1811+
1812+ bind_addr = local_files.get_bind_address()
1813+ if bind_addr is not None and bind_addr != '':
1814+ from socket import inet_ntop, inet_pton
1815+ from socket import error as socketerror
1816+ try:
1817+ # There are more than dotted decimal quad to
1818+ # contend with. 183468213 == 0xaef80b5 ==
1819+ # 0xa.0xef.0x80.0xb5 == 012.0357.0200.0265 ==
1820+ # 10.239.128.181. Just ask the system instead.
1821+ addr_standard_form = inet_ntop(inet_pton(bind_addr))
1822+ except socketerror:
1823+ log.warn("bind address is illegal, %r", bind_addr)
1824+ log.warn("(If couchdb does understand it, please open a bug!)")
1825+ sys.exit(1)
1826+
1827+ if addr_standard_form.startswith("127."): # entire /8 is local.
1828+ log.warn("couchdb bound to addr %r; cannot accept connections",
1829+ bind_addr)
1830+ elif addr_standard_form == "::1": # no addr block on v6. Just one.
1831+ log.warn("couchdb bound to addr %r; cannot accept connections",
1832+ bind_addr)
1833+
1834+ unique_identifiers = couchdb_io.get_my_host_unique_id()
1835+ if unique_identifiers is None:
1836+ log.warn("No unique hostaccount id is set, so pairing not enabled.")
1837+ sys.exit(2)
1838+
1839+ port = desktopcouch.find_port()
1840+ beacons = [dbus_io.LocationAdvertisement(port, "desktopcouch " + i)
1841+ for i in unique_identifiers]
1842+ for b in beacons:
1843+ b.publish()
1844+
1845+ dbus_io.discover_services(None, None, True)
1846+
1847+ try:
1848+ dbus_io.maintain_discovered_servers()
1849+ t = task.LoopingCall(replicate_local_databases_to_paired_hosts, port)
1850+ t.start(600)
1851+
1852+ # TODO: port may change, so every so often, check it and
1853+ # perhaps refresh the beacons.
1854+
1855+ reactor.run()
1856+ finally:
1857+ for b in beacons:
1858+ b.unpublish()
1859+
1860+ finally:
1861+ log.info("Quitting.")
1862+
1863+if __name__ == "__main__":
1864+ import sys
1865+
1866+ main(sys.argv)
1867
1868=== added file 'bin/desktopcouch-service'
1869--- bin/desktopcouch-service 1970-01-01 00:00:00 +0000
1870+++ bin/desktopcouch-service 2009-08-26 17:49:19 +0000
1871@@ -0,0 +1,71 @@
1872+#!/usr/bin/python
1873+# Copyright 2009 Canonical Ltd.
1874+#
1875+# This file is part of desktopcouch.
1876+#
1877+# desktopcouch is free software: you can redistribute it and/or modify
1878+# it under the terms of the GNU Lesser General Public License version 3
1879+# as published by the Free Software Foundation.
1880+#
1881+# desktopcouch is distributed in the hope that it will be useful,
1882+# but WITHOUT ANY WARRANTY; without even the implied warranty of
1883+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1884+# GNU Lesser General Public License for more details.
1885+#
1886+# You should have received a copy of the GNU Lesser General Public License
1887+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
1888+#
1889+# Authors: Stuart Langridge <stuart.langridge@canonical.com>
1890+# Tim Cole <tim.cole@canonical.com>
1891+
1892+"""CouchDB port advertiser.
1893+
1894+A command-line utility which exports a
1895+desktopCouch.getPort method on the bus which returns
1896+that port, so other apps (specifically, the contacts API) can work out
1897+where CouchDB is running so it can be talked to.
1898+
1899+Calculates the port number by looking in the CouchDB log.
1900+
1901+If CouchDB is not running, then run the script to start it and then
1902+start advertising the port.
1903+
1904+This file should be started by D-Bus activation.
1905+
1906+"""
1907+
1908+import desktopcouch
1909+from desktopcouch import local_files
1910+
1911+import re
1912+from errno import ENOENT
1913+from dbus.mainloop.glib import DBusGMainLoop
1914+import dbus.service, gobject, os, errno, time
1915+DBusGMainLoop(set_as_default=True)
1916+
1917+class PortAdvertiser(dbus.service.Object):
1918+ "Advertise the discovered port number on the D-Bus Session bus"
1919+ def __init__(self, death):
1920+ bus_name = dbus.service.BusName("org.desktopcouch.CouchDB",
1921+ bus=dbus.SessionBus())
1922+ self.death = death
1923+ dbus.service.Object.__init__(self, object_path="/", bus_name=bus_name)
1924+
1925+ @dbus.service.method(dbus_interface='org.desktopcouch.CouchDB',
1926+ in_signature='', out_signature='i')
1927+ def getPort(self):
1928+ "Exported method to return the port"
1929+ return int(desktopcouch.find_port())
1930+
1931+ @dbus.service.method(dbus_interface='org.desktopcouch.CouchDB',
1932+ in_signature='', out_signature='')
1933+ def quit(self):
1934+ "Exported method to quit the program"
1935+ self.death()
1936+
1937+if __name__ == "__main__":
1938+
1939+ # Advertise the port
1940+ mainloop = gobject.MainLoop()
1941+ portAdvertiser = PortAdvertiser(mainloop.quit)
1942+ mainloop.run()
1943
1944=== added file 'bin/desktopcouch-stop'
1945--- bin/desktopcouch-stop 1970-01-01 00:00:00 +0000
1946+++ bin/desktopcouch-stop 2009-07-24 19:32:52 +0000
1947@@ -0,0 +1,36 @@
1948+#!/usr/bin/python
1949+# Copyright 2009 Canonical Ltd.
1950+#
1951+# This file is part of desktopcouch.
1952+#
1953+# desktopcouch is free software: you can redistribute it and/or modify
1954+# it under the terms of the GNU Lesser General Public License version 3
1955+# as published by the Free Software Foundation.
1956+#
1957+# desktopcouch is distributed in the hope that it will be useful,
1958+# but WITHOUT ANY WARRANTY; without even the implied warranty of
1959+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1960+# GNU Lesser General Public License for more details.
1961+#
1962+# You should have received a copy of the GNU Lesser General Public License
1963+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
1964+#
1965+# Author: Stuart Langridge <stuart.langridge@canonical.com>
1966+"""
1967+Stop local CouchDB server.
1968+"""
1969+import subprocess, sys
1970+from desktopcouch import local_files
1971+
1972+local_exec = local_files.COUCH_EXEC_COMMAND + ["-k"]
1973+try:
1974+ retcode = subprocess.call(local_exec, shell=False)
1975+ if retcode < 0:
1976+ print >> sys.stderr, "Child was terminated by signal", -retcode
1977+ elif retcode > 0:
1978+ print >> sys.stderr, "Child returned", retcode
1979+except OSError, e:
1980+ print >> sys.stderr, "Execution failed: %s: %s" % (e, local_exec)
1981+ exit(1)
1982+
1983+
1984
1985=== added directory 'contrib'
1986=== added file 'contrib/mocker.py'
1987--- contrib/mocker.py 1970-01-01 00:00:00 +0000
1988+++ contrib/mocker.py 2009-08-06 13:57:30 +0000
1989@@ -0,0 +1,2068 @@
1990+"""
1991+Copyright (c) 2007 Gustavo Niemeyer <gustavo@niemeyer.net>
1992+
1993+Graceful platform for test doubles in Python (mocks, stubs, fakes, and dummies).
1994+"""
1995+import __builtin__
1996+import tempfile
1997+import unittest
1998+import inspect
1999+import shutil
2000+import types
2001+import sys
2002+import os
2003+import gc
2004+
2005+
2006+if sys.version_info < (2, 4):
2007+ from sets import Set as set # pragma: nocover
2008+
2009+
2010+__all__ = ["Mocker", "expect", "IS", "CONTAINS", "IN", "MATCH",
2011+ "ANY", "ARGS", "KWARGS"]
2012+
2013+
2014+__author__ = "Gustavo Niemeyer <gustavo@niemeyer.net>"
2015+__license__ = "PSF License"
2016+__version__ = "0.10.1"
2017+
2018+
2019+ERROR_PREFIX = "[Mocker] "
2020+
2021+
2022+# --------------------------------------------------------------------
2023+# Exceptions
2024+
2025+class MatchError(AssertionError):
2026+ """Raised when an unknown expression is seen in playback mode."""
2027+
2028+
2029+# --------------------------------------------------------------------
2030+# Helper for chained-style calling.
2031+
2032+class expect(object):
2033+ """This is a simple helper that allows a different call-style.
2034+
2035+ With this class one can comfortably do chaining of calls to the
2036+ mocker object responsible by the object being handled. For instance::
2037+
2038+ expect(obj.attr).result(3).count(1, 2)
2039+
2040+ Is the same as::
2041+
2042+ obj.attr
2043+ mocker.result(3)
2044+ mocker.count(1, 2)
2045+
2046+ """
2047+
2048+ def __init__(self, mock, attr=None):
2049+ self._mock = mock
2050+ self._attr = attr
2051+
2052+ def __getattr__(self, attr):
2053+ return self.__class__(self._mock, attr)
2054+
2055+ def __call__(self, *args, **kwargs):
2056+ getattr(self._mock.__mocker__, self._attr)(*args, **kwargs)
2057+ return self
2058+
2059+
2060+# --------------------------------------------------------------------
2061+# Extensions to Python's unittest.
2062+
2063+class MockerTestCase(unittest.TestCase):
2064+ """unittest.TestCase subclass with Mocker support.
2065+
2066+ @ivar mocker: The mocker instance.
2067+
2068+ This is a convenience only. Mocker may easily be used with the
2069+ standard C{unittest.TestCase} class if wanted.
2070+
2071+ Test methods have a Mocker instance available on C{self.mocker}.
2072+ At the end of each test method, expectations of the mocker will
2073+ be verified, and any requested changes made to the environment
2074+ will be restored.
2075+
2076+ In addition to the integration with Mocker, this class provides
2077+ a few additional helper methods.
2078+ """
2079+
2080+ expect = expect
2081+
2082+ def __init__(self, methodName="runTest"):
2083+ # So here is the trick: we take the real test method, wrap it on
2084+ # a function that do the job we have to do, and insert it in the
2085+ # *instance* dictionary, so that getattr() will return our
2086+ # replacement rather than the class method.
2087+ test_method = getattr(self, methodName, None)
2088+ if test_method is not None:
2089+ def test_method_wrapper():
2090+ try:
2091+ result = test_method()
2092+ except:
2093+ raise
2094+ else:
2095+ if (self.mocker.is_recording() and
2096+ self.mocker.get_events()):
2097+ raise RuntimeError("Mocker must be put in replay "
2098+ "mode with self.mocker.replay()")
2099+ if (hasattr(result, "addCallback") and
2100+ hasattr(result, "addErrback")):
2101+ def verify(result):
2102+ self.mocker.verify()
2103+ return result
2104+ result.addCallback(verify)
2105+ else:
2106+ self.mocker.verify()
2107+ return result
2108+ # Copy all attributes from the original method..
2109+ for attr in dir(test_method):
2110+ # .. unless they're present in our wrapper already.
2111+ if not hasattr(test_method_wrapper, attr) or attr == "__doc__":
2112+ setattr(test_method_wrapper, attr,
2113+ getattr(test_method, attr))
2114+ setattr(self, methodName, test_method_wrapper)
2115+
2116+ # We could overload run() normally, but other well-known testing
2117+ # frameworks do it as well, and some of them won't call the super,
2118+ # which might mean that cleanup wouldn't happen. With that in mind,
2119+ # we make integration easier by using the following trick.
2120+ run_method = self.run
2121+ def run_wrapper(*args, **kwargs):
2122+ try:
2123+ return run_method(*args, **kwargs)
2124+ finally:
2125+ self.__cleanup()
2126+ self.run = run_wrapper
2127+
2128+ self.mocker = Mocker()
2129+
2130+ self.__cleanup_funcs = []
2131+ self.__cleanup_paths = []
2132+
2133+ super(MockerTestCase, self).__init__(methodName)
2134+
2135+ def __cleanup(self):
2136+ for path in self.__cleanup_paths:
2137+ if os.path.isfile(path):
2138+ os.unlink(path)
2139+ elif os.path.isdir(path):
2140+ shutil.rmtree(path)
2141+ self.mocker.restore()
2142+ for func, args, kwargs in self.__cleanup_funcs:
2143+ func(*args, **kwargs)
2144+
2145+ def addCleanup(self, func, *args, **kwargs):
2146+ self.__cleanup_funcs.append((func, args, kwargs))
2147+
2148+ def makeFile(self, content=None, suffix="", prefix="tmp", basename=None,
2149+ dirname=None, path=None):
2150+ """Create a temporary file and return the path to it.
2151+
2152+ @param content: Initial content for the file.
2153+ @param suffix: Suffix to be given to the file's basename.
2154+ @param prefix: Prefix to be given to the file's basename.
2155+ @param basename: Full basename for the file.
2156+ @param dirname: Put file inside this directory.
2157+
2158+ The file is removed after the test runs.
2159+ """
2160+ if path is not None:
2161+ self.__cleanup_paths.append(path)
2162+ elif basename is not None:
2163+ if dirname is None:
2164+ dirname = tempfile.mkdtemp()
2165+ self.__cleanup_paths.append(dirname)
2166+ path = os.path.join(dirname, basename)
2167+ else:
2168+ fd, path = tempfile.mkstemp(suffix, prefix, dirname)
2169+ self.__cleanup_paths.append(path)
2170+ os.close(fd)
2171+ if content is None:
2172+ os.unlink(path)
2173+ if content is not None:
2174+ file = open(path, "w")
2175+ file.write(content)
2176+ file.close()
2177+ return path
2178+
2179+ def makeDir(self, suffix="", prefix="tmp", dirname=None, path=None):
2180+ """Create a temporary directory and return the path to it.
2181+
2182+ @param suffix: Suffix to be given to the file's basename.
2183+ @param prefix: Prefix to be given to the file's basename.
2184+ @param dirname: Put directory inside this parent directory.
2185+
2186+ The directory is removed after the test runs.
2187+ """
2188+ if path is not None:
2189+ os.makedirs(path)
2190+ else:
2191+ path = tempfile.mkdtemp(suffix, prefix, dirname)
2192+ self.__cleanup_paths.append(path)
2193+ return path
2194+
2195+ def failUnlessIs(self, first, second, msg=None):
2196+ """Assert that C{first} is the same object as C{second}."""
2197+ if first is not second:
2198+ raise self.failureException(msg or "%r is not %r" % (first, second))
2199+
2200+ def failIfIs(self, first, second, msg=None):
2201+ """Assert that C{first} is not the same object as C{second}."""
2202+ if first is second:
2203+ raise self.failureException(msg or "%r is %r" % (first, second))
2204+
2205+ def failUnlessIn(self, first, second, msg=None):
2206+ """Assert that C{first} is contained in C{second}."""
2207+ if first not in second:
2208+ raise self.failureException(msg or "%r not in %r" % (first, second))
2209+
2210+ def failUnlessStartsWith(self, first, second, msg=None):
2211+ """Assert that C{first} starts with C{second}."""
2212+ if first[:len(second)] != second:
2213+ raise self.failureException(msg or "%r doesn't start with %r" %
2214+ (first, second))
2215+
2216+ def failIfStartsWith(self, first, second, msg=None):
2217+ """Assert that C{first} doesn't start with C{second}."""
2218+ if first[:len(second)] == second:
2219+ raise self.failureException(msg or "%r starts with %r" %
2220+ (first, second))
2221+
2222+ def failUnlessEndsWith(self, first, second, msg=None):
2223+ """Assert that C{first} starts with C{second}."""
2224+ if first[len(first)-len(second):] != second:
2225+ raise self.failureException(msg or "%r doesn't end with %r" %
2226+ (first, second))
2227+
2228+ def failIfEndsWith(self, first, second, msg=None):
2229+ """Assert that C{first} doesn't start with C{second}."""
2230+ if first[len(first)-len(second):] == second:
2231+ raise self.failureException(msg or "%r ends with %r" %
2232+ (first, second))
2233+
2234+ def failIfIn(self, first, second, msg=None):
2235+ """Assert that C{first} is not contained in C{second}."""
2236+ if first in second:
2237+ raise self.failureException(msg or "%r in %r" % (first, second))
2238+
2239+ def failUnlessApproximates(self, first, second, tolerance, msg=None):
2240+ """Assert that C{first} is near C{second} by at most C{tolerance}."""
2241+ if abs(first - second) > tolerance:
2242+ raise self.failureException(msg or "abs(%r - %r) > %r" %
2243+ (first, second, tolerance))
2244+
2245+ def failIfApproximates(self, first, second, tolerance, msg=None):
2246+ """Assert that C{first} is far from C{second} by at least C{tolerance}.
2247+ """
2248+ if abs(first - second) <= tolerance:
2249+ raise self.failureException(msg or "abs(%r - %r) <= %r" %
2250+ (first, second, tolerance))
2251+
2252+ def failUnlessMethodsMatch(self, first, second):
2253+ """Assert that public methods in C{first} are present in C{second}.
2254+
2255+ This method asserts that all public methods found in C{first} are also
2256+ present in C{second} and accept the same arguments. C{first} may
2257+ have its own private methods, though, and may not have all methods
2258+ found in C{second}. Note that if a private method in C{first} matches
2259+ the name of one in C{second}, their specification is still compared.
2260+
2261+ This is useful to verify if a fake or stub class have the same API as
2262+ the real class being simulated.
2263+ """
2264+ first_methods = dict(inspect.getmembers(first, inspect.ismethod))
2265+ second_methods = dict(inspect.getmembers(second, inspect.ismethod))
2266+ for name, first_method in first_methods.items():
2267+ first_argspec = inspect.getargspec(first_method)
2268+ first_formatted = inspect.formatargspec(*first_argspec)
2269+
2270+ second_method = second_methods.get(name)
2271+ if second_method is None:
2272+ if name[:1] == "_":
2273+ continue # First may have its own private methods.
2274+ raise self.failureException("%s.%s%s not present in %s" %
2275+ (first.__name__, name, first_formatted, second.__name__))
2276+
2277+ second_argspec = inspect.getargspec(second_method)
2278+ if first_argspec != second_argspec:
2279+ second_formatted = inspect.formatargspec(*second_argspec)
2280+ raise self.failureException("%s.%s%s != %s.%s%s" %
2281+ (first.__name__, name, first_formatted,
2282+ second.__name__, name, second_formatted))
2283+
2284+
2285+ assertIs = failUnlessIs
2286+ assertIsNot = failIfIs
2287+ assertIn = failUnlessIn
2288+ assertNotIn = failIfIn
2289+ assertStartsWith = failUnlessStartsWith
2290+ assertNotStartsWith = failIfStartsWith
2291+ assertEndsWith = failUnlessEndsWith
2292+ assertNotEndsWith = failIfEndsWith
2293+ assertApproximates = failUnlessApproximates
2294+ assertNotApproximates = failIfApproximates
2295+ assertMethodsMatch = failUnlessMethodsMatch
2296+
2297+ # The following are missing in Python < 2.4.
2298+ assertTrue = unittest.TestCase.failUnless
2299+ assertFalse = unittest.TestCase.failIf
2300+
2301+ # The following is provided for compatibility with Twisted's trial.
2302+ assertIdentical = assertIs
2303+ assertNotIdentical = assertIsNot
2304+ failUnlessIdentical = failUnlessIs
2305+ failIfIdentical = failIfIs
2306+
2307+
2308+# --------------------------------------------------------------------
2309+# Mocker.
2310+
2311+class classinstancemethod(object):
2312+
2313+ def __init__(self, method):
2314+ self.method = method
2315+
2316+ def __get__(self, obj, cls=None):
2317+ def bound_method(*args, **kwargs):
2318+ return self.method(cls, obj, *args, **kwargs)
2319+ return bound_method
2320+
2321+
2322+class MockerBase(object):
2323+ """Controller of mock objects.
2324+
2325+ A mocker instance is used to command recording and replay of
2326+ expectations on any number of mock objects.
2327+
2328+ Expectations should be expressed for the mock object while in
2329+ record mode (the initial one) by using the mock object itself,
2330+ and using the mocker (and/or C{expect()} as a helper) to define
2331+ additional behavior for each event. For instance::
2332+
2333+ mock = mocker.mock()
2334+ mock.hello()
2335+ mocker.result("Hi!")
2336+ mocker.replay()
2337+ assert mock.hello() == "Hi!"
2338+ mock.restore()
2339+ mock.verify()
2340+
2341+ In this short excerpt a mock object is being created, then an
2342+ expectation of a call to the C{hello()} method was recorded, and
2343+ when called the method should return the value C{10}. Then, the
2344+ mocker is put in replay mode, and the expectation is satisfied by
2345+ calling the C{hello()} method, which indeed returns 10. Finally,
2346+ a call to the L{restore()} method is performed to undo any needed
2347+ changes made in the environment, and the L{verify()} method is
2348+ called to ensure that all defined expectations were met.
2349+
2350+ The same logic can be expressed more elegantly using the
2351+ C{with mocker:} statement, as follows::
2352+
2353+ mock = mocker.mock()
2354+ mock.hello()
2355+ mocker.result("Hi!")
2356+ with mocker:
2357+ assert mock.hello() == "Hi!"
2358+
2359+ Also, the MockerTestCase class, which integrates the mocker on
2360+ a unittest.TestCase subclass, may be used to reduce the overhead
2361+ of controlling the mocker. A test could be written as follows::
2362+
2363+ class SampleTest(MockerTestCase):
2364+
2365+ def test_hello(self):
2366+ mock = self.mocker.mock()
2367+ mock.hello()
2368+ self.mocker.result("Hi!")
2369+ self.mocker.replay()
2370+ self.assertEquals(mock.hello(), "Hi!")
2371+ """
2372+
2373+ _recorders = []
2374+
2375+ # For convenience only.
2376+ on = expect
2377+
2378+ class __metaclass__(type):
2379+ def __init__(self, name, bases, dict):
2380+ # Make independent lists on each subclass, inheriting from parent.
2381+ self._recorders = list(getattr(self, "_recorders", ()))
2382+
2383+ def __init__(self):
2384+ self._recorders = self._recorders[:]
2385+ self._events = []
2386+ self._recording = True
2387+ self._ordering = False
2388+ self._last_orderer = None
2389+
2390+ def is_recording(self):
2391+ """Return True if in recording mode, False if in replay mode.
2392+
2393+ Recording is the initial state.
2394+ """
2395+ return self._recording
2396+
2397+ def replay(self):
2398+ """Change to replay mode, where recorded events are reproduced.
2399+
2400+ If already in replay mode, the mocker will be restored, with all
2401+ expectations reset, and then put again in replay mode.
2402+
2403+ An alternative and more comfortable way to replay changes is
2404+ using the 'with' statement, as follows::
2405+
2406+ mocker = Mocker()
2407+ <record events>
2408+ with mocker:
2409+ <reproduce events>
2410+
2411+ The 'with' statement will automatically put mocker in replay
2412+ mode, and will also verify if all events were correctly reproduced
2413+ at the end (using L{verify()}), and also restore any changes done
2414+ in the environment (with L{restore()}).
2415+
2416+ Also check the MockerTestCase class, which integrates the
2417+ unittest.TestCase class with mocker.
2418+ """
2419+ if not self._recording:
2420+ for event in self._events:
2421+ event.restore()
2422+ else:
2423+ self._recording = False
2424+ for event in self._events:
2425+ event.replay()
2426+
2427+ def restore(self):
2428+ """Restore changes in the environment, and return to recording mode.
2429+
2430+ This should always be called after the test is complete (succeeding
2431+ or not). There are ways to call this method automatically on
2432+ completion (e.g. using a C{with mocker:} statement, or using the
2433+ L{MockerTestCase} class.
2434+ """
2435+ if not self._recording:
2436+ self._recording = True
2437+ for event in self._events:
2438+ event.restore()
2439+
2440+ def reset(self):
2441+ """Reset the mocker state.
2442+
2443+ This will restore environment changes, if currently in replay
2444+ mode, and then remove all events previously recorded.
2445+ """
2446+ if not self._recording:
2447+ self.restore()
2448+ self.unorder()
2449+ del self._events[:]
2450+
2451+ def get_events(self):
2452+ """Return all recorded events."""
2453+ return self._events[:]
2454+
2455+ def add_event(self, event):
2456+ """Add an event.
2457+
2458+ This method is used internally by the implementation, and
2459+ shouldn't be needed on normal mocker usage.
2460+ """
2461+ self._events.append(event)
2462+ if self._ordering:
2463+ orderer = event.add_task(Orderer(event.path))
2464+ if self._last_orderer:
2465+ orderer.add_dependency(self._last_orderer)
2466+ self._last_orderer = orderer
2467+ return event
2468+
2469+ def verify(self):
2470+ """Check if all expectations were met, and raise AssertionError if not.
2471+
2472+ The exception message will include a nice description of which
2473+ expectations were not met, and why.
2474+ """
2475+ errors = []
2476+ for event in self._events:
2477+ try:
2478+ event.verify()
2479+ except AssertionError, e:
2480+ error = str(e)
2481+ if not error:
2482+ raise RuntimeError("Empty error message from %r"
2483+ % event)
2484+ errors.append(error)
2485+ if errors:
2486+ message = [ERROR_PREFIX + "Unmet expectations:", ""]
2487+ for error in errors:
2488+ lines = error.splitlines()
2489+ message.append("=> " + lines.pop(0))
2490+ message.extend([" " + line for line in lines])
2491+ message.append("")
2492+ raise AssertionError(os.linesep.join(message))
2493+
2494+ def mock(self, spec_and_type=None, spec=None, type=None,
2495+ name=None, count=True):
2496+ """Return a new mock object.
2497+
2498+ @param spec_and_type: Handy positional argument which sets both
2499+ spec and type.
2500+ @param spec: Method calls will be checked for correctness against
2501+ the given class.
2502+ @param type: If set, the Mock's __class__ attribute will return
2503+ the given type. This will make C{isinstance()} calls
2504+ on the object work.
2505+ @param name: Name for the mock object, used in the representation of
2506+ expressions. The name is rarely needed, as it's usually
2507+ guessed correctly from the variable name used.
2508+ @param count: If set to false, expressions may be executed any number
2509+ of times, unless an expectation is explicitly set using
2510+ the L{count()} method. By default, expressions are
2511+ expected once.
2512+ """
2513+ if spec_and_type is not None:
2514+ spec = type = spec_and_type
2515+ return Mock(self, spec=spec, type=type, name=name, count=count)
2516+
2517+ def proxy(self, object, spec=True, type=True, name=None, count=True,
2518+ passthrough=True):
2519+ """Return a new mock object which proxies to the given object.
2520+
2521+ Proxies are useful when only part of the behavior of an object
2522+ is to be mocked. Unknown expressions may be passed through to
2523+ the real implementation implicitly (if the C{passthrough} argument
2524+ is True), or explicitly (using the L{passthrough()} method
2525+ on the event).
2526+
2527+ @param object: Real object to be proxied, and replaced by the mock
2528+ on replay mode. It may also be an "import path",
2529+ such as C{"time.time"}, in which case the object
2530+ will be the C{time} function from the C{time} module.
2531+ @param spec: Method calls will be checked for correctness against
2532+ the given object, which may be a class or an instance
2533+ where attributes will be looked up. Defaults to the
2534+ the C{object} parameter. May be set to None explicitly,
2535+ in which case spec checking is disabled. Checks may
2536+ also be disabled explicitly on a per-event basis with
2537+ the L{nospec()} method.
2538+ @param type: If set, the Mock's __class__ attribute will return
2539+ the given type. This will make C{isinstance()} calls
2540+ on the object work. Defaults to the type of the
2541+ C{object} parameter. May be set to None explicitly.
2542+ @param name: Name for the mock object, used in the representation of
2543+ expressions. The name is rarely needed, as it's usually
2544+ guessed correctly from the variable name used.
2545+ @param count: If set to false, expressions may be executed any number
2546+ of times, unless an expectation is explicitly set using
2547+ the L{count()} method. By default, expressions are
2548+ expected once.
2549+ @param passthrough: If set to False, passthrough of actions on the
2550+ proxy to the real object will only happen when
2551+ explicitly requested via the L{passthrough()}
2552+ method.
2553+ """
2554+ if isinstance(object, basestring):
2555+ if name is None:
2556+ name = object
2557+ import_stack = object.split(".")
2558+ attr_stack = []
2559+ while import_stack:
2560+ module_path = ".".join(import_stack)
2561+ try:
2562+ object = __import__(module_path, {}, {}, [""])
2563+ except ImportError:
2564+ attr_stack.insert(0, import_stack.pop())
2565+ if not import_stack:
2566+ raise
2567+ continue
2568+ else:
2569+ for attr in attr_stack:
2570+ object = getattr(object, attr)
2571+ break
2572+ if spec is True:
2573+ spec = object
2574+ if type is True:
2575+ type = __builtin__.type(object)
2576+ return Mock(self, spec=spec, type=type, object=object,
2577+ name=name, count=count, passthrough=passthrough)
2578+
2579+ def replace(self, object, spec=True, type=True, name=None, count=True,
2580+ passthrough=True):
2581+ """Create a proxy, and replace the original object with the mock.
2582+
2583+ On replay, the original object will be replaced by the returned
2584+ proxy in all dictionaries found in the running interpreter via
2585+ the garbage collecting system. This should cover module
2586+ namespaces, class namespaces, instance namespaces, and so on.
2587+
2588+ @param object: Real object to be proxied, and replaced by the mock
2589+ on replay mode. It may also be an "import path",
2590+ such as C{"time.time"}, in which case the object
2591+ will be the C{time} function from the C{time} module.
2592+ @param spec: Method calls will be checked for correctness against
2593+ the given object, which may be a class or an instance
2594+ where attributes will be looked up. Defaults to the
2595+ the C{object} parameter. May be set to None explicitly,
2596+ in which case spec checking is disabled. Checks may
2597+ also be disabled explicitly on a per-event basis with
2598+ the L{nospec()} method.
2599+ @param type: If set, the Mock's __class__ attribute will return
2600+ the given type. This will make C{isinstance()} calls
2601+ on the object work. Defaults to the type of the
2602+ C{object} parameter. May be set to None explicitly.
2603+ @param name: Name for the mock object, used in the representation of
2604+ expressions. The name is rarely needed, as it's usually
2605+ guessed correctly from the variable name used.
2606+ @param passthrough: If set to False, passthrough of actions on the
2607+ proxy to the real object will only happen when
2608+ explicitly requested via the L{passthrough()}
2609+ method.
2610+ """
2611+ mock = self.proxy(object, spec, type, name, count, passthrough)
2612+ event = self._get_replay_restore_event()
2613+ event.add_task(ProxyReplacer(mock))
2614+ return mock
2615+
2616+ def patch(self, object, spec=True):
2617+ """Patch an existing object to reproduce recorded events.
2618+
2619+ @param object: Class or instance to be patched.
2620+ @param spec: Method calls will be checked for correctness against
2621+ the given object, which may be a class or an instance
2622+ where attributes will be looked up. Defaults to the
2623+ the C{object} parameter. May be set to None explicitly,
2624+ in which case spec checking is disabled. Checks may
2625+ also be disabled explicitly on a per-event basis with
2626+ the L{nospec()} method.
2627+
2628+ The result of this method is still a mock object, which can be
2629+ used like any other mock object to record events. The difference
2630+ is that when the mocker is put on replay mode, the *real* object
2631+ will be modified to behave according to recorded expectations.
2632+
2633+ Patching works in individual instances, and also in classes.
2634+ When an instance is patched, recorded events will only be
2635+ considered on this specific instance, and other instances should
2636+ behave normally. When a class is patched, the reproduction of
2637+ events will be considered on any instance of this class once
2638+ created (collectively).
2639+
2640+ Observe that, unlike with proxies which catch only events done
2641+ through the mock object, *all* accesses to recorded expectations
2642+ will be considered; even these coming from the object itself
2643+ (e.g. C{self.hello()} is considered if this method was patched).
2644+ While this is a very powerful feature, and many times the reason
2645+ to use patches in the first place, it's important to keep this
2646+ behavior in mind.
2647+
2648+ Patching of the original object only takes place when the mocker
2649+ is put on replay mode, and the patched object will be restored
2650+ to its original state once the L{restore()} method is called
2651+ (explicitly, or implicitly with alternative conventions, such as
2652+ a C{with mocker:} block, or a MockerTestCase class).
2653+ """
2654+ if spec is True:
2655+ spec = object
2656+ patcher = Patcher()
2657+ event = self._get_replay_restore_event()
2658+ event.add_task(patcher)
2659+ mock = Mock(self, object=object, patcher=patcher,
2660+ passthrough=True, spec=spec)
2661+ object.__mocker_mock__ = mock
2662+ return mock
2663+
2664+ def act(self, path):
2665+ """This is called by mock objects whenever something happens to them.
2666+
2667+ This method is part of the implementation between the mocker
2668+ and mock objects.
2669+ """
2670+ if self._recording:
2671+ event = self.add_event(Event(path))
2672+ for recorder in self._recorders:
2673+ recorder(self, event)
2674+ return Mock(self, path)
2675+ else:
2676+ # First run events that may run, then run unsatisfied events, then
2677+ # ones not previously run. We put the index in the ordering tuple
2678+ # instead of the actual event because we want a stable sort
2679+ # (ordering between 2 events is undefined).
2680+ events = self._events
2681+ order = [(events[i].satisfied()*2 + events[i].has_run(), i)
2682+ for i in range(len(events))]
2683+ order.sort()
2684+ postponed = None
2685+ for weight, i in order:
2686+ event = events[i]
2687+ if event.matches(path):
2688+ if event.may_run(path):
2689+ return event.run(path)
2690+ elif postponed is None:
2691+ postponed = event
2692+ if postponed is not None:
2693+ return postponed.run(path)
2694+ raise MatchError(ERROR_PREFIX + "Unexpected expression: %s" % path)
2695+
2696+ def get_recorders(cls, self):
2697+ """Return recorders associated with this mocker class or instance.
2698+
2699+ This method may be called on mocker instances and also on mocker
2700+ classes. See the L{add_recorder()} method for more information.
2701+ """
2702+ return (self or cls)._recorders[:]
2703+ get_recorders = classinstancemethod(get_recorders)
2704+
2705+ def add_recorder(cls, self, recorder):
2706+ """Add a recorder to this mocker class or instance.
2707+
2708+ @param recorder: Callable accepting C{(mocker, event)} as parameters.
2709+
2710+ This is part of the implementation of mocker.
2711+
2712+ All registered recorders are called for translating events that
2713+ happen during recording into expectations to be met once the state
2714+ is switched to replay mode.
2715+
2716+ This method may be called on mocker instances and also on mocker
2717+ classes. When called on a class, the recorder will be used by
2718+ all instances, and also inherited on subclassing. When called on
2719+ instances, the recorder is added only to the given instance.
2720+ """
2721+ (self or cls)._recorders.append(recorder)
2722+ return recorder
2723+ add_recorder = classinstancemethod(add_recorder)
2724+
2725+ def remove_recorder(cls, self, recorder):
2726+ """Remove the given recorder from this mocker class or instance.
2727+
2728+ This method may be called on mocker classes and also on mocker
2729+ instances. See the L{add_recorder()} method for more information.
2730+ """
2731+ (self or cls)._recorders.remove(recorder)
2732+ remove_recorder = classinstancemethod(remove_recorder)
2733+
2734+ def result(self, value):
2735+ """Make the last recorded event return the given value on replay.
2736+
2737+ @param value: Object to be returned when the event is replayed.
2738+ """
2739+ self.call(lambda *args, **kwargs: value)
2740+
2741+ def generate(self, sequence):
2742+ """Last recorded event will return a generator with the given sequence.
2743+
2744+ @param sequence: Sequence of values to be generated.
2745+ """
2746+ def generate(*args, **kwargs):
2747+ for value in sequence:
2748+ yield value
2749+ self.call(generate)
2750+
2751+ def throw(self, exception):
2752+ """Make the last recorded event raise the given exception on replay.
2753+
2754+ @param exception: Class or instance of exception to be raised.
2755+ """
2756+ def raise_exception(*args, **kwargs):
2757+ raise exception
2758+ self.call(raise_exception)
2759+
2760+ def call(self, func):
2761+ """Make the last recorded event cause the given function to be called.
2762+
2763+ @param func: Function to be called.
2764+
2765+ The result of the function will be used as the event result.
2766+ """
2767+ self._events[-1].add_task(FunctionRunner(func))
2768+
2769+ def count(self, min, max=False):
2770+ """Last recorded event must be replayed between min and max times.
2771+
2772+ @param min: Minimum number of times that the event must happen.
2773+ @param max: Maximum number of times that the event must happen. If
2774+ not given, it defaults to the same value of the C{min}
2775+ parameter. If set to None, there is no upper limit, and
2776+ the expectation is met as long as it happens at least
2777+ C{min} times.
2778+ """
2779+ event = self._events[-1]
2780+ for task in event.get_tasks():
2781+ if isinstance(task, RunCounter):
2782+ event.remove_task(task)
2783+ event.add_task(RunCounter(min, max))
2784+
2785+ def is_ordering(self):
2786+ """Return true if all events are being ordered.
2787+
2788+ See the L{order()} method.
2789+ """
2790+ return self._ordering
2791+
2792+ def unorder(self):
2793+ """Disable the ordered mode.
2794+
2795+ See the L{order()} method for more information.
2796+ """
2797+ self._ordering = False
2798+ self._last_orderer = None
2799+
2800+ def order(self, *path_holders):
2801+ """Create an expectation of order between two or more events.
2802+
2803+ @param path_holders: Objects returned as the result of recorded events.
2804+
2805+ By default, mocker won't force events to happen precisely in
2806+ the order they were recorded. Calling this method will change
2807+ this behavior so that events will only match if reproduced in
2808+ the correct order.
2809+
2810+ There are two ways in which this method may be used. Which one
2811+ is used in a given occasion depends only on convenience.
2812+
2813+ If no arguments are passed, the mocker will be put in a mode where
2814+ all the recorded events following the method call will only be met
2815+ if they happen in order. When that's used, the mocker may be put
2816+ back in unordered mode by calling the L{unorder()} method, or by
2817+ using a 'with' block, like so::
2818+
2819+ with mocker.ordered():
2820+ <record events>
2821+
2822+ In this case, only expressions in <record events> will be ordered,
2823+ and the mocker will be back in unordered mode after the 'with' block.
2824+
2825+ The second way to use it is by specifying precisely which events
2826+ should be ordered. As an example::
2827+
2828+ mock = mocker.mock()
2829+ expr1 = mock.hello()
2830+ expr2 = mock.world
2831+ expr3 = mock.x.y.z
2832+ mocker.order(expr1, expr2, expr3)
2833+
2834+ This method of ordering only works when the expression returns
2835+ another object.
2836+
2837+ Also check the L{after()} and L{before()} methods, which are
2838+ alternative ways to perform this.
2839+ """
2840+ if not path_holders:
2841+ self._ordering = True
2842+ return OrderedContext(self)
2843+
2844+ last_orderer = None
2845+ for path_holder in path_holders:
2846+ if type(path_holder) is Path:
2847+ path = path_holder
2848+ else:
2849+ path = path_holder.__mocker_path__
2850+ for event in self._events:
2851+ if event.path is path:
2852+ for task in event.get_tasks():
2853+ if isinstance(task, Orderer):
2854+ orderer = task
2855+ break
2856+ else:
2857+ orderer = Orderer(path)
2858+ event.add_task(orderer)
2859+ if last_orderer:
2860+ orderer.add_dependency(last_orderer)
2861+ last_orderer = orderer
2862+ break
2863+
2864+ def after(self, *path_holders):
2865+ """Last recorded event must happen after events referred to.
2866+
2867+ @param path_holders: Objects returned as the result of recorded events
2868+ which should happen before the last recorded event
2869+
2870+ As an example, the idiom::
2871+
2872+ expect(mock.x).after(mock.y, mock.z)
2873+
2874+ is an alternative way to say::
2875+
2876+ expr_x = mock.x
2877+ expr_y = mock.y
2878+ expr_z = mock.z
2879+ mocker.order(expr_y, expr_x)
2880+ mocker.order(expr_z, expr_x)
2881+
2882+ See L{order()} for more information.
2883+ """
2884+ last_path = self._events[-1].path
2885+ for path_holder in path_holders:
2886+ self.order(path_holder, last_path)
2887+
2888+ def before(self, *path_holders):
2889+ """Last recorded event must happen before events referred to.
2890+
2891+ @param path_holders: Objects returned as the result of recorded events
2892+ which should happen after the last recorded event
2893+
2894+ As an example, the idiom::
2895+
2896+ expect(mock.x).before(mock.y, mock.z)
2897+
2898+ is an alternative way to say::
2899+
2900+ expr_x = mock.x
2901+ expr_y = mock.y
2902+ expr_z = mock.z
2903+ mocker.order(expr_x, expr_y)
2904+ mocker.order(expr_x, expr_z)
2905+
2906+ See L{order()} for more information.
2907+ """
2908+ last_path = self._events[-1].path
2909+ for path_holder in path_holders:
2910+ self.order(last_path, path_holder)
2911+
2912+ def nospec(self):
2913+ """Don't check method specification of real object on last event.
2914+
2915+ By default, when using a mock created as the result of a call to
2916+ L{proxy()}, L{replace()}, and C{patch()}, or when passing the spec
2917+ attribute to the L{mock()} method, method calls on the given object
2918+ are checked for correctness against the specification of the real
2919+ object (or the explicitly provided spec).
2920+
2921+ This method will disable that check specifically for the last
2922+ recorded event.
2923+ """
2924+ event = self._events[-1]
2925+ for task in event.get_tasks():
2926+ if isinstance(task, SpecChecker):
2927+ event.remove_task(task)
2928+
2929+ def passthrough(self, result_callback=None):
2930+ """Make the last recorded event run on the real object once seen.
2931+
2932+ @param result_callback: If given, this function will be called with
2933+ the result of the *real* method call as the only argument.
2934+
2935+ This can only be used on proxies, as returned by the L{proxy()}
2936+ and L{replace()} methods, or on mocks representing patched objects,
2937+ as returned by the L{patch()} method.
2938+ """
2939+ event = self._events[-1]
2940+ if event.path.root_object is None:
2941+ raise TypeError("Mock object isn't a proxy")
2942+ event.add_task(PathExecuter(result_callback))
2943+
2944+ def __enter__(self):
2945+ """Enter in a 'with' context. This will run replay()."""
2946+ self.replay()
2947+ return self
2948+
2949+ def __exit__(self, type, value, traceback):
2950+ """Exit from a 'with' context.
2951+
2952+ This will run restore() at all times, but will only run verify()
2953+ if the 'with' block itself hasn't raised an exception. Exceptions
2954+ in that block are never swallowed.
2955+ """
2956+ self.restore()
2957+ if type is None:
2958+ self.verify()
2959+ return False
2960+
2961+ def _get_replay_restore_event(self):
2962+ """Return unique L{ReplayRestoreEvent}, creating if needed.
2963+
2964+ Some tasks only want to replay/restore. When that's the case,
2965+ they shouldn't act on other events during replay. Also, they
2966+ can all be put in a single event when that's the case. Thus,
2967+ we add a single L{ReplayRestoreEvent} as the first element of
2968+ the list.
2969+ """
2970+ if not self._events or type(self._events[0]) != ReplayRestoreEvent:
2971+ self._events.insert(0, ReplayRestoreEvent())
2972+ return self._events[0]
2973+
2974+
2975+class OrderedContext(object):
2976+
2977+ def __init__(self, mocker):
2978+ self._mocker = mocker
2979+
2980+ def __enter__(self):
2981+ return None
2982+
2983+ def __exit__(self, type, value, traceback):
2984+ self._mocker.unorder()
2985+
2986+
2987+class Mocker(MockerBase):
2988+ __doc__ = MockerBase.__doc__
2989+
2990+# Decorator to add recorders on the standard Mocker class.
2991+recorder = Mocker.add_recorder
2992+
2993+
2994+# --------------------------------------------------------------------
2995+# Mock object.
2996+
2997+class Mock(object):
2998+
2999+ def __init__(self, mocker, path=None, name=None, spec=None, type=None,
3000+ object=None, passthrough=False, patcher=None, count=True):
3001+ self.__mocker__ = mocker
3002+ self.__mocker_path__ = path or Path(self, object)
3003+ self.__mocker_name__ = name
3004+ self.__mocker_spec__ = spec
3005+ self.__mocker_object__ = object
3006+ self.__mocker_passthrough__ = passthrough
3007+ self.__mocker_patcher__ = patcher
3008+ self.__mocker_replace__ = False
3009+ self.__mocker_type__ = type
3010+ self.__mocker_count__ = count
3011+
3012+ def __mocker_act__(self, kind, args=(), kwargs={}, object=None):
3013+ if self.__mocker_name__ is None:
3014+ self.__mocker_name__ = find_object_name(self, 2)
3015+ action = Action(kind, args, kwargs, self.__mocker_path__)
3016+ path = self.__mocker_path__ + action
3017+ if object is not None:
3018+ path.root_object = object
3019+ try:
3020+ return self.__mocker__.act(path)
3021+ except MatchError, exception:
3022+ root_mock = path.root_mock
3023+ if (path.root_object is not None and
3024+ root_mock.__mocker_passthrough__):
3025+ return path.execute(path.root_object)
3026+ # Reinstantiate to show raise statement on traceback, and
3027+ # also to make the traceback shown shorter.
3028+ raise MatchError(str(exception))
3029+ except AssertionError, e:
3030+ lines = str(e).splitlines()
3031+ message = [ERROR_PREFIX + "Unmet expectation:", ""]
3032+ message.append("=> " + lines.pop(0))
3033+ message.extend([" " + line for line in lines])
3034+ message.append("")
3035+ raise AssertionError(os.linesep.join(message))
3036+
3037+ def __getattribute__(self, name):
3038+ if name.startswith("__mocker_"):
3039+ return super(Mock, self).__getattribute__(name)
3040+ if name == "__class__":
3041+ if self.__mocker__.is_recording() or self.__mocker_type__ is None:
3042+ return type(self)
3043+ return self.__mocker_type__
3044+ return self.__mocker_act__("getattr", (name,))
3045+
3046+ def __setattr__(self, name, value):
3047+ if name.startswith("__mocker_"):
3048+ return super(Mock, self).__setattr__(name, value)
3049+ return self.__mocker_act__("setattr", (name, value))
3050+
3051+ def __delattr__(self, name):
3052+ return self.__mocker_act__("delattr", (name,))
3053+
3054+ def __call__(self, *args, **kwargs):
3055+ return self.__mocker_act__("call", args, kwargs)
3056+
3057+ def __contains__(self, value):
3058+ return self.__mocker_act__("contains", (value,))
3059+
3060+ def __getitem__(self, key):
3061+ return self.__mocker_act__("getitem", (key,))
3062+
3063+ def __setitem__(self, key, value):
3064+ return self.__mocker_act__("setitem", (key, value))
3065+
3066+ def __delitem__(self, key):
3067+ return self.__mocker_act__("delitem", (key,))
3068+
3069+ def __len__(self):
3070+ # MatchError is turned on an AttributeError so that list() and
3071+ # friends act properly when trying to get length hints on
3072+ # something that doesn't offer them.
3073+ try:
3074+ result = self.__mocker_act__("len")
3075+ except MatchError, e:
3076+ raise AttributeError(str(e))
3077+ if type(result) is Mock:
3078+ return 0
3079+ return result
3080+
3081+ def __nonzero__(self):
3082+ try:
3083+ return self.__mocker_act__("nonzero")
3084+ except MatchError, e:
3085+ return True
3086+
3087+ def __iter__(self):
3088+ # XXX On py3k, when next() becomes __next__(), we'll be able
3089+ # to return the mock itself because it will be considered
3090+ # an iterator (we'll be mocking __next__ as well, which we
3091+ # can't now).
3092+ result = self.__mocker_act__("iter")
3093+ if type(result) is Mock:
3094+ return iter([])
3095+ return result
3096+
3097+ # When adding a new action kind here, also add support for it on
3098+ # Action.execute() and Path.__str__().
3099+
3100+
3101+def find_object_name(obj, depth=0):
3102+ """Try to detect how the object is named on a previous scope."""
3103+ try:
3104+ frame = sys._getframe(depth+1)
3105+ except:
3106+ return None
3107+ for name, frame_obj in frame.f_locals.iteritems():
3108+ if frame_obj is obj:
3109+ return name
3110+ self = frame.f_locals.get("self")
3111+ if self is not None:
3112+ try:
3113+ items = list(self.__dict__.iteritems())
3114+ except:
3115+ pass
3116+ else:
3117+ for name, self_obj in items:
3118+ if self_obj is obj:
3119+ return name
3120+ return None
3121+
3122+
3123+# --------------------------------------------------------------------
3124+# Action and path.
3125+
3126+class Action(object):
3127+
3128+ def __init__(self, kind, args, kwargs, path=None):
3129+ self.kind = kind
3130+ self.args = args
3131+ self.kwargs = kwargs
3132+ self.path = path
3133+ self._execute_cache = {}
3134+
3135+ def __repr__(self):
3136+ if self.path is None:
3137+ return "Action(%r, %r, %r)" % (self.kind, self.args, self.kwargs)
3138+ return "Action(%r, %r, %r, %r)" % \
3139+ (self.kind, self.args, self.kwargs, self.path)
3140+
3141+ def __eq__(self, other):
3142+ return (self.kind == other.kind and
3143+ self.args == other.args and
3144+ self.kwargs == other.kwargs)
3145+
3146+ def __ne__(self, other):
3147+ return not self.__eq__(other)
3148+
3149+ def matches(self, other):
3150+ return (self.kind == other.kind and
3151+ match_params(self.args, self.kwargs, other.args, other.kwargs))
3152+
3153+ def execute(self, object):
3154+ # This caching scheme may fail if the object gets deallocated before
3155+ # the action, as the id might get reused. It's somewhat easy to fix
3156+ # that with a weakref callback. For our uses, though, the object
3157+ # should never get deallocated before the action itself, so we'll
3158+ # just keep it simple.
3159+ if id(object) in self._execute_cache:
3160+ return self._execute_cache[id(object)]
3161+ execute = getattr(object, "__mocker_execute__", None)
3162+ if execute is not None:
3163+ result = execute(self, object)
3164+ else:
3165+ kind = self.kind
3166+ if kind == "getattr":
3167+ result = getattr(object, self.args[0])
3168+ elif kind == "setattr":
3169+ result = setattr(object, self.args[0], self.args[1])
3170+ elif kind == "delattr":
3171+ result = delattr(object, self.args[0])
3172+ elif kind == "call":
3173+ result = object(*self.args, **self.kwargs)
3174+ elif kind == "contains":
3175+ result = self.args[0] in object
3176+ elif kind == "getitem":
3177+ result = object[self.args[0]]
3178+ elif kind == "setitem":
3179+ result = object[self.args[0]] = self.args[1]
3180+ elif kind == "delitem":
3181+ del object[self.args[0]]
3182+ result = None
3183+ elif kind == "len":
3184+ result = len(object)
3185+ elif kind == "nonzero":
3186+ result = bool(object)
3187+ elif kind == "iter":
3188+ result = iter(object)
3189+ else:
3190+ raise RuntimeError("Don't know how to execute %r kind." % kind)
3191+ self._execute_cache[id(object)] = result
3192+ return result
3193+
3194+
3195+class Path(object):
3196+
3197+ def __init__(self, root_mock, root_object=None, actions=()):
3198+ self.root_mock = root_mock
3199+ self.root_object = root_object
3200+ self.actions = tuple(actions)
3201+ self.__mocker_replace__ = False
3202+
3203+ def parent_path(self):
3204+ if not self.actions:
3205+ return None
3206+ return self.actions[-1].path
3207+ parent_path = property(parent_path)
3208+
3209+ def __add__(self, action):
3210+ """Return a new path which includes the given action at the end."""
3211+ return self.__class__(self.root_mock, self.root_object,
3212+ self.actions + (action,))
3213+
3214+ def __eq__(self, other):
3215+ """Verify if the two paths are equal.
3216+
3217+ Two paths are equal if they refer to the same mock object, and
3218+ have the actions with equal kind, args and kwargs.
3219+ """
3220+ if (self.root_mock is not other.root_mock or
3221+ self.root_object is not other.root_object or
3222+ len(self.actions) != len(other.actions)):
3223+ return False
3224+ for action, other_action in zip(self.actions, other.actions):
3225+ if action != other_action:
3226+ return False
3227+ return True
3228+
3229+ def matches(self, other):
3230+ """Verify if the two paths are equivalent.
3231+
3232+ Two paths are equal if they refer to the same mock object, and
3233+ have the same actions performed on them.
3234+ """
3235+ if (self.root_mock is not other.root_mock or
3236+ len(self.actions) != len(other.actions)):
3237+ return False
3238+ for action, other_action in zip(self.actions, other.actions):
3239+ if not action.matches(other_action):
3240+ return False
3241+ return True
3242+
3243+ def execute(self, object):
3244+ """Execute all actions sequentially on object, and return result.
3245+ """
3246+ for action in self.actions:
3247+ object = action.execute(object)
3248+ return object
3249+
3250+ def __str__(self):
3251+ """Transform the path into a nice string such as obj.x.y('z')."""
3252+ result = self.root_mock.__mocker_name__ or "<mock>"
3253+ for action in self.actions:
3254+ if action.kind == "getattr":
3255+ result = "%s.%s" % (result, action.args[0])
3256+ elif action.kind == "setattr":
3257+ result = "%s.%s = %r" % (result, action.args[0], action.args[1])
3258+ elif action.kind == "delattr":
3259+ result = "del %s.%s" % (result, action.args[0])
3260+ elif action.kind == "call":
3261+ args = [repr(x) for x in action.args]
3262+ items = list(action.kwargs.iteritems())
3263+ items.sort()
3264+ for pair in items:
3265+ args.append("%s=%r" % pair)
3266+ result = "%s(%s)" % (result, ", ".join(args))
3267+ elif action.kind == "contains":
3268+ result = "%r in %s" % (action.args[0], result)
3269+ elif action.kind == "getitem":
3270+ result = "%s[%r]" % (result, action.args[0])
3271+ elif action.kind == "setitem":
3272+ result = "%s[%r] = %r" % (result, action.args[0],
3273+ action.args[1])
3274+ elif action.kind == "delitem":
3275+ result = "del %s[%r]" % (result, action.args[0])
3276+ elif action.kind == "len":
3277+ result = "len(%s)" % result
3278+ elif action.kind == "nonzero":
3279+ result = "bool(%s)" % result
3280+ elif action.kind == "iter":
3281+ result = "iter(%s)" % result
3282+ else:
3283+ raise RuntimeError("Don't know how to format kind %r" %
3284+ action.kind)
3285+ return result
3286+
3287+
3288+class SpecialArgument(object):
3289+ """Base for special arguments for matching parameters."""
3290+
3291+ def __init__(self, object=None):
3292+ self.object = object
3293+
3294+ def __repr__(self):
3295+ if self.object is None:
3296+ return self.__class__.__name__
3297+ else:
3298+ return "%s(%r)" % (self.__class__.__name__, self.object)
3299+
3300+ def matches(self, other):
3301+ return True
3302+
3303+ def __eq__(self, other):
3304+ return type(other) == type(self) and self.object == other.object
3305+
3306+
3307+class ANY(SpecialArgument):
3308+ """Matches any single argument."""
3309+
3310+ANY = ANY()
3311+
3312+
3313+class ARGS(SpecialArgument):
3314+ """Matches zero or more positional arguments."""
3315+
3316+ARGS = ARGS()
3317+
3318+
3319+class KWARGS(SpecialArgument):
3320+ """Matches zero or more keyword arguments."""
3321+
3322+KWARGS = KWARGS()
3323+
3324+
3325+class IS(SpecialArgument):
3326+
3327+ def matches(self, other):
3328+ return self.object is other
3329+
3330+ def __eq__(self, other):
3331+ return type(other) == type(self) and self.object is other.object
3332+
3333+
3334+class CONTAINS(SpecialArgument):
3335+
3336+ def matches(self, other):
3337+ try:
3338+ other.__contains__
3339+ except AttributeError:
3340+ try:
3341+ iter(other)
3342+ except TypeError:
3343+ # If an object can't be iterated, and has no __contains__
3344+ # hook, it'd blow up on the test below. We test this in
3345+ # advance to prevent catching more errors than we really
3346+ # want.
3347+ return False
3348+ return self.object in other
3349+
3350+
3351+class IN(SpecialArgument):
3352+
3353+ def matches(self, other):
3354+ return other in self.object
3355+
3356+
3357+class MATCH(SpecialArgument):
3358+
3359+ def matches(self, other):
3360+ return bool(self.object(other))
3361+
3362+ def __eq__(self, other):
3363+ return type(other) == type(self) and self.object is other.object
3364+
3365+
3366+def match_params(args1, kwargs1, args2, kwargs2):
3367+ """Match the two sets of parameters, considering special parameters."""
3368+
3369+ has_args = ARGS in args1
3370+ has_kwargs = KWARGS in args1
3371+
3372+ if has_kwargs:
3373+ args1 = [arg1 for arg1 in args1 if arg1 is not KWARGS]
3374+ elif len(kwargs1) != len(kwargs2):
3375+ return False
3376+
3377+ if not has_args and len(args1) != len(args2):
3378+ return False
3379+
3380+ # Either we have the same number of kwargs, or unknown keywords are
3381+ # accepted (KWARGS was used), so check just the ones in kwargs1.
3382+ for key, arg1 in kwargs1.iteritems():
3383+ if key not in kwargs2:
3384+ return False
3385+ arg2 = kwargs2[key]
3386+ if isinstance(arg1, SpecialArgument):
3387+ if not arg1.matches(arg2):
3388+ return False
3389+ elif arg1 != arg2:
3390+ return False
3391+
3392+ # Keywords match. Now either we have the same number of
3393+ # arguments, or ARGS was used. If ARGS wasn't used, arguments
3394+ # must match one-on-one necessarily.
3395+ if not has_args:
3396+ for arg1, arg2 in zip(args1, args2):
3397+ if isinstance(arg1, SpecialArgument):
3398+ if not arg1.matches(arg2):
3399+ return False
3400+ elif arg1 != arg2:
3401+ return False
3402+ return True
3403+
3404+ # Easy choice. Keywords are matching, and anything on args is accepted.
3405+ if (ARGS,) == args1:
3406+ return True
3407+
3408+ # We have something different there. If we don't have positional
3409+ # arguments on the original call, it can't match.
3410+ if not args2:
3411+ # Unless we have just several ARGS (which is bizarre, but..).
3412+ for arg1 in args1:
3413+ if arg1 is not ARGS:
3414+ return False
3415+ return True
3416+
3417+ # Ok, all bets are lost. We have to actually do the more expensive
3418+ # matching. This is an algorithm based on the idea of the Levenshtein
3419+ # Distance between two strings, but heavily hacked for this purpose.
3420+ args2l = len(args2)
3421+ if args1[0] is ARGS:
3422+ args1 = args1[1:]
3423+ array = [0]*args2l
3424+ else:
3425+ array = [1]*args2l
3426+ for i in range(len(args1)):
3427+ last = array[0]
3428+ if args1[i] is ARGS:
3429+ for j in range(1, args2l):
3430+ last, array[j] = array[j], min(array[j-1], array[j], last)
3431+ else:
3432+ array[0] = i or int(args1[i] != args2[0])
3433+ for j in range(1, args2l):
3434+ last, array[j] = array[j], last or int(args1[i] != args2[j])
3435+ if 0 not in array:
3436+ return False
3437+ if array[-1] != 0:
3438+ return False
3439+ return True
3440+
3441+
3442+# --------------------------------------------------------------------
3443+# Event and task base.
3444+
3445+class Event(object):
3446+ """Aggregation of tasks that keep track of a recorded action.
3447+
3448+ An event represents something that may or may not happen while the
3449+ mocked environment is running, such as an attribute access, or a
3450+ method call. The event is composed of several tasks that are
3451+ orchestrated together to create a composed meaning for the event,
3452+ including for which actions it should be run, what happens when it
3453+ runs, and what's the expectations about the actions run.
3454+ """
3455+
3456+ def __init__(self, path=None):
3457+ self.path = path
3458+ self._tasks = []
3459+ self._has_run = False
3460+
3461+ def add_task(self, task):
3462+ """Add a new task to this taks."""
3463+ self._tasks.append(task)
3464+ return task
3465+
3466+ def remove_task(self, task):
3467+ self._tasks.remove(task)
3468+
3469+ def get_tasks(self):
3470+ return self._tasks[:]
3471+
3472+ def matches(self, path):
3473+ """Return true if *all* tasks match the given path."""
3474+ for task in self._tasks:
3475+ if not task.matches(path):
3476+ return False
3477+ return bool(self._tasks)
3478+
3479+ def has_run(self):
3480+ return self._has_run
3481+
3482+ def may_run(self, path):
3483+ """Verify if any task would certainly raise an error if run.
3484+
3485+ This will call the C{may_run()} method on each task and return
3486+ false if any of them returns false.
3487+ """
3488+ for task in self._tasks:
3489+ if not task.may_run(path):
3490+ return False
3491+ return True
3492+
3493+ def run(self, path):
3494+ """Run all tasks with the given action.
3495+
3496+ @param path: The path of the expression run.
3497+
3498+ Running an event means running all of its tasks individually and in
3499+ order. An event should only ever be run if all of its tasks claim to
3500+ match the given action.
3501+
3502+ The result of this method will be the last result of a task
3503+ which isn't None, or None if they're all None.
3504+ """
3505+ self._has_run = True
3506+ result = None
3507+ errors = []
3508+ for task in self._tasks:
3509+ try:
3510+ task_result = task.run(path)
3511+ except AssertionError, e:
3512+ error = str(e)
3513+ if not error:
3514+ raise RuntimeError("Empty error message from %r" % task)
3515+ errors.append(error)
3516+ else:
3517+ if task_result is not None:
3518+ result = task_result
3519+ if errors:
3520+ message = [str(self.path)]
3521+ if str(path) != message[0]:
3522+ message.append("- Run: %s" % path)
3523+ for error in errors:
3524+ lines = error.splitlines()
3525+ message.append("- " + lines.pop(0))
3526+ message.extend([" " + line for line in lines])
3527+ raise AssertionError(os.linesep.join(message))
3528+ return result
3529+
3530+ def satisfied(self):
3531+ """Return true if all tasks are satisfied.
3532+
3533+ Being satisfied means that there are no unmet expectations.
3534+ """
3535+ for task in self._tasks:
3536+ try:
3537+ task.verify()
3538+ except AssertionError:
3539+ return False
3540+ return True
3541+
3542+ def verify(self):
3543+ """Run verify on all tasks.
3544+
3545+ The verify method is supposed to raise an AssertionError if the
3546+ task has unmet expectations, with a one-line explanation about
3547+ why this item is unmet. This method should be safe to be called
3548+ multiple times without side effects.
3549+ """
3550+ errors = []
3551+ for task in self._tasks:
3552+ try:
3553+ task.verify()
3554+ except AssertionError, e:
3555+ error = str(e)
3556+ if not error:
3557+ raise RuntimeError("Empty error message from %r" % task)
3558+ errors.append(error)
3559+ if errors:
3560+ message = [str(self.path)]
3561+ for error in errors:
3562+ lines = error.splitlines()
3563+ message.append("- " + lines.pop(0))
3564+ message.extend([" " + line for line in lines])
3565+ raise AssertionError(os.linesep.join(message))
3566+
3567+ def replay(self):
3568+ """Put all tasks in replay mode."""
3569+ self._has_run = False
3570+ for task in self._tasks:
3571+ task.replay()
3572+
3573+ def restore(self):
3574+ """Restore the state of all tasks."""
3575+ for task in self._tasks:
3576+ task.restore()
3577+
3578+
3579+class ReplayRestoreEvent(Event):
3580+ """Helper event for tasks which need replay/restore but shouldn't match."""
3581+
3582+ def matches(self, path):
3583+ return False
3584+
3585+
3586+class Task(object):
3587+ """Element used to track one specific aspect on an event.
3588+
3589+ A task is responsible for adding any kind of logic to an event.
3590+ Examples of that are counting the number of times the event was
3591+ made, verifying parameters if any, and so on.
3592+ """
3593+
3594+ def matches(self, path):
3595+ """Return true if the task is supposed to be run for the given path.
3596+ """
3597+ return True
3598+
3599+ def may_run(self, path):
3600+ """Return false if running this task would certainly raise an error."""
3601+ return True
3602+
3603+ def run(self, path):
3604+ """Perform the task item, considering that the given action happened.
3605+ """
3606+
3607+ def verify(self):
3608+ """Raise AssertionError if expectations for this item are unmet.
3609+
3610+ The verify method is supposed to raise an AssertionError if the
3611+ task has unmet expectations, with a one-line explanation about
3612+ why this item is unmet. This method should be safe to be called
3613+ multiple times without side effects.
3614+ """
3615+
3616+ def replay(self):
3617+ """Put the task in replay mode.
3618+
3619+ Any expectations of the task should be reset.
3620+ """
3621+
3622+ def restore(self):
3623+ """Restore any environmental changes made by the task.
3624+
3625+ Verify should continue to work after this is called.
3626+ """
3627+
3628+
3629+# --------------------------------------------------------------------
3630+# Task implementations.
3631+
3632+class OnRestoreCaller(Task):
3633+ """Call a given callback when restoring."""
3634+
3635+ def __init__(self, callback):
3636+ self._callback = callback
3637+
3638+ def restore(self):
3639+ self._callback()
3640+
3641+
3642+class PathMatcher(Task):
3643+ """Match the action path against a given path."""
3644+
3645+ def __init__(self, path):
3646+ self.path = path
3647+
3648+ def matches(self, path):
3649+ return self.path.matches(path)
3650+
3651+def path_matcher_recorder(mocker, event):
3652+ event.add_task(PathMatcher(event.path))
3653+
3654+Mocker.add_recorder(path_matcher_recorder)
3655+
3656+
3657+class RunCounter(Task):
3658+ """Task which verifies if the number of runs are within given boundaries.
3659+ """
3660+
3661+ def __init__(self, min, max=False):
3662+ self.min = min
3663+ if max is None:
3664+ self.max = sys.maxint
3665+ elif max is False:
3666+ self.max = min
3667+ else:
3668+ self.max = max
3669+ self._runs = 0
3670+
3671+ def replay(self):
3672+ self._runs = 0
3673+
3674+ def may_run(self, path):
3675+ return self._runs < self.max
3676+
3677+ def run(self, path):
3678+ self._runs += 1
3679+ if self._runs > self.max:
3680+ self.verify()
3681+
3682+ def verify(self):
3683+ if not self.min <= self._runs <= self.max:
3684+ if self._runs < self.min:
3685+ raise AssertionError("Performed fewer times than expected.")
3686+ raise AssertionError("Performed more times than expected.")
3687+
3688+
3689+class ImplicitRunCounter(RunCounter):
3690+ """RunCounter inserted by default on any event.
3691+
3692+ This is a way to differentiate explicitly added counters and
3693+ implicit ones.
3694+ """
3695+
3696+def run_counter_recorder(mocker, event):
3697+ """Any event may be repeated once, unless disabled by default."""
3698+ if event.path.root_mock.__mocker_count__:
3699+ event.add_task(ImplicitRunCounter(1))
3700+
3701+Mocker.add_recorder(run_counter_recorder)
3702+
3703+def run_counter_removal_recorder(mocker, event):
3704+ """
3705+ Events created by getattr actions which lead to other events
3706+ may be repeated any number of times. For that, we remove implicit
3707+ run counters of any getattr actions leading to the current one.
3708+ """
3709+ parent_path = event.path.parent_path
3710+ for event in mocker.get_events()[::-1]:
3711+ if (event.path is parent_path and
3712+ event.path.actions[-1].kind == "getattr"):
3713+ for task in event.get_tasks():
3714+ if type(task) is ImplicitRunCounter:
3715+ event.remove_task(task)
3716+
3717+Mocker.add_recorder(run_counter_removal_recorder)
3718+
3719+
3720+class MockReturner(Task):
3721+ """Return a mock based on the action path."""
3722+
3723+ def __init__(self, mocker):
3724+ self.mocker = mocker
3725+
3726+ def run(self, path):
3727+ return Mock(self.mocker, path)
3728+
3729+def mock_returner_recorder(mocker, event):
3730+ """Events that lead to other events must return mock objects."""
3731+ parent_path = event.path.parent_path
3732+ for event in mocker.get_events():
3733+ if event.path is parent_path:
3734+ for task in event.get_tasks():
3735+ if isinstance(task, MockReturner):
3736+ break
3737+ else:
3738+ event.add_task(MockReturner(mocker))
3739+ break
3740+
3741+Mocker.add_recorder(mock_returner_recorder)
3742+
3743+
3744+class FunctionRunner(Task):
3745+ """Task that runs a function everything it's run.
3746+
3747+ Arguments of the last action in the path are passed to the function,
3748+ and the function result is also returned.
3749+ """
3750+
3751+ def __init__(self, func):
3752+ self._func = func
3753+
3754+ def run(self, path):
3755+ action = path.actions[-1]
3756+ return self._func(*action.args, **action.kwargs)
3757+
3758+
3759+class PathExecuter(Task):
3760+ """Task that executes a path in the real object, and returns the result."""
3761+
3762+ def __init__(self, result_callback=None):
3763+ self._result_callback = result_callback
3764+
3765+ def get_result_callback(self):
3766+ return self._result_callback
3767+
3768+ def run(self, path):
3769+ result = path.execute(path.root_object)
3770+ if self._result_callback is not None:
3771+ self._result_callback(result)
3772+ return result
3773+
3774+
3775+class Orderer(Task):
3776+ """Task to establish an order relation between two events.
3777+
3778+ An orderer task will only match once all its dependencies have
3779+ been run.
3780+ """
3781+
3782+ def __init__(self, path):
3783+ self.path = path
3784+ self._run = False
3785+ self._dependencies = []
3786+
3787+ def replay(self):
3788+ self._run = False
3789+
3790+ def has_run(self):
3791+ return self._run
3792+
3793+ def may_run(self, path):
3794+ for dependency in self._dependencies:
3795+ if not dependency.has_run():
3796+ return False
3797+ return True
3798+
3799+ def run(self, path):
3800+ for dependency in self._dependencies:
3801+ if not dependency.has_run():
3802+ raise AssertionError("Should be after: %s" % dependency.path)
3803+ self._run = True
3804+
3805+ def add_dependency(self, orderer):
3806+ self._dependencies.append(orderer)
3807+
3808+ def get_dependencies(self):
3809+ return self._dependencies
3810+
3811+
3812+class SpecChecker(Task):
3813+ """Task to check if arguments of the last action conform to a real method.
3814+ """
3815+
3816+ def __init__(self, method):
3817+ self._method = method
3818+ self._unsupported = False
3819+
3820+ if method:
3821+ try:
3822+ self._args, self._varargs, self._varkwargs, self._defaults = \
3823+ inspect.getargspec(method)
3824+ except TypeError:
3825+ self._unsupported = True
3826+ else:
3827+ if self._defaults is None:
3828+ self._defaults = ()
3829+ if type(method) is type(self.run):
3830+ self._args = self._args[1:]
3831+
3832+ def get_method(self):
3833+ return self._method
3834+
3835+ def _raise(self, message):
3836+ spec = inspect.formatargspec(self._args, self._varargs,
3837+ self._varkwargs, self._defaults)
3838+ raise AssertionError("Specification is %s%s: %s" %
3839+ (self._method.__name__, spec, message))
3840+
3841+ def verify(self):
3842+ if not self._method:
3843+ raise AssertionError("Method not found in real specification")
3844+
3845+ def may_run(self, path):
3846+ try:
3847+ self.run(path)
3848+ except AssertionError:
3849+ return False
3850+ return True
3851+
3852+ def run(self, path):
3853+ if not self._method:
3854+ raise AssertionError("Method not found in real specification")
3855+ if self._unsupported:
3856+ return # Can't check it. Happens with builtin functions. :-(
3857+ action = path.actions[-1]
3858+ obtained_len = len(action.args)
3859+ obtained_kwargs = action.kwargs.copy()
3860+ nodefaults_len = len(self._args) - len(self._defaults)
3861+ for i, name in enumerate(self._args):
3862+ if i < obtained_len and name in action.kwargs:
3863+ self._raise("%r provided twice" % name)
3864+ if (i >= obtained_len and i < nodefaults_len and
3865+ name not in action.kwargs):
3866+ self._raise("%r not provided" % name)
3867+ obtained_kwargs.pop(name, None)
3868+ if obtained_len > len(self._args) and not self._varargs:
3869+ self._raise("too many args provided")
3870+ if obtained_kwargs and not self._varkwargs:
3871+ self._raise("unknown kwargs: %s" % ", ".join(obtained_kwargs))
3872+
3873+def spec_checker_recorder(mocker, event):
3874+ spec = event.path.root_mock.__mocker_spec__
3875+ if spec:
3876+ actions = event.path.actions
3877+ if len(actions) == 1:
3878+ if actions[0].kind == "call":
3879+ method = getattr(spec, "__call__", None)
3880+ event.add_task(SpecChecker(method))
3881+ elif len(actions) == 2:
3882+ if actions[0].kind == "getattr" and actions[1].kind == "call":
3883+ method = getattr(spec, actions[0].args[0], None)
3884+ event.add_task(SpecChecker(method))
3885+
3886+Mocker.add_recorder(spec_checker_recorder)
3887+
3888+
3889+class ProxyReplacer(Task):
3890+ """Task which installs and deinstalls proxy mocks.
3891+
3892+ This task will replace a real object by a mock in all dictionaries
3893+ found in the running interpreter via the garbage collecting system.
3894+ """
3895+
3896+ def __init__(self, mock):
3897+ self.mock = mock
3898+ self.__mocker_replace__ = False
3899+
3900+ def replay(self):
3901+ global_replace(self.mock.__mocker_object__, self.mock)
3902+
3903+ def restore(self):
3904+ global_replace(self.mock, self.mock.__mocker_object__)
3905+
3906+
3907+def global_replace(remove, install):
3908+ """Replace object 'remove' with object 'install' on all dictionaries."""
3909+ for referrer in gc.get_referrers(remove):
3910+ if (type(referrer) is dict and
3911+ referrer.get("__mocker_replace__", True)):
3912+ for key, value in referrer.items():
3913+ if value is remove:
3914+ referrer[key] = install
3915+
3916+
3917+class Undefined(object):
3918+
3919+ def __repr__(self):
3920+ return "Undefined"
3921+
3922+Undefined = Undefined()
3923+
3924+
3925+class Patcher(Task):
3926+
3927+ def __init__(self):
3928+ super(Patcher, self).__init__()
3929+ self._monitored = {} # {kind: {id(object): object}}
3930+ self._patched = {}
3931+
3932+ def is_monitoring(self, obj, kind):
3933+ monitored = self._monitored.get(kind)
3934+ if monitored:
3935+ if id(obj) in monitored:
3936+ return True
3937+ cls = type(obj)
3938+ if issubclass(cls, type):
3939+ cls = obj
3940+ bases = set([id(base) for base in cls.__mro__])
3941+ bases.intersection_update(monitored)
3942+ return bool(bases)
3943+ return False
3944+
3945+ def monitor(self, obj, kind):
3946+ if kind not in self._monitored:
3947+ self._monitored[kind] = {}
3948+ self._monitored[kind][id(obj)] = obj
3949+
3950+ def patch_attr(self, obj, attr, value):
3951+ original = obj.__dict__.get(attr, Undefined)
3952+ self._patched[id(obj), attr] = obj, attr, original
3953+ setattr(obj, attr, value)
3954+
3955+ def get_unpatched_attr(self, obj, attr):
3956+ cls = type(obj)
3957+ if issubclass(cls, type):
3958+ cls = obj
3959+ result = Undefined
3960+ for mro_cls in cls.__mro__:
3961+ key = (id(mro_cls), attr)
3962+ if key in self._patched:
3963+ result = self._patched[key][2]
3964+ if result is not Undefined:
3965+ break
3966+ elif attr in mro_cls.__dict__:
3967+ result = mro_cls.__dict__.get(attr, Undefined)
3968+ break
3969+ if isinstance(result, object) and hasattr(type(result), "__get__"):
3970+ if cls is obj:
3971+ obj = None
3972+ return result.__get__(obj, cls)
3973+ return result
3974+
3975+ def _get_kind_attr(self, kind):
3976+ if kind == "getattr":
3977+ return "__getattribute__"
3978+ return "__%s__" % kind
3979+
3980+ def replay(self):
3981+ for kind in self._monitored:
3982+ attr = self._get_kind_attr(kind)
3983+ seen = set()
3984+ for obj in self._monitored[kind].itervalues():
3985+ cls = type(obj)
3986+ if issubclass(cls, type):
3987+ cls = obj
3988+ if cls not in seen:
3989+ seen.add(cls)
3990+ unpatched = getattr(cls, attr, Undefined)
3991+ self.patch_attr(cls, attr,
3992+ PatchedMethod(kind, unpatched,
3993+ self.is_monitoring))
3994+ self.patch_attr(cls, "__mocker_execute__",
3995+ self.execute)
3996+
3997+ def restore(self):
3998+ for obj, attr, original in self._patched.itervalues():
3999+ if original is Undefined:
4000+ delattr(obj, attr)
4001+ else:
4002+ setattr(obj, attr, original)
4003+ self._patched.clear()
4004+
4005+ def execute(self, action, object):
4006+ attr = self._get_kind_attr(action.kind)
4007+ unpatched = self.get_unpatched_attr(object, attr)
4008+ try:
4009+ return unpatched(*action.args, **action.kwargs)
4010+ except AttributeError:
4011+ if action.kind == "getattr":
4012+ # The normal behavior of Python is to try __getattribute__,
4013+ # and if it raises AttributeError, try __getattr__. We've
4014+ # tried the unpatched __getattribute__ above, and we'll now
4015+ # try __getattr__.
4016+ try:
4017+ __getattr__ = unpatched("__getattr__")
4018+ except AttributeError:
4019+ pass
4020+ else:
4021+ return __getattr__(*action.args, **action.kwargs)
4022+ raise
4023+
4024+
4025+class PatchedMethod(object):
4026+
4027+ def __init__(self, kind, unpatched, is_monitoring):
4028+ self._kind = kind
4029+ self._unpatched = unpatched
4030+ self._is_monitoring = is_monitoring
4031+
4032+ def __get__(self, obj, cls=None):
4033+ object = obj or cls
4034+ if not self._is_monitoring(object, self._kind):
4035+ return self._unpatched.__get__(obj, cls)
4036+ def method(*args, **kwargs):
4037+ if self._kind == "getattr" and args[0].startswith("__mocker_"):
4038+ return self._unpatched.__get__(obj, cls)(args[0])
4039+ mock = object.__mocker_mock__
4040+ return mock.__mocker_act__(self._kind, args, kwargs, object)
4041+ return method
4042+
4043+ def __call__(self, obj, *args, **kwargs):
4044+ # At least with __getattribute__, Python seems to use *both* the
4045+ # descriptor API and also call the class attribute directly. It
4046+ # looks like an interpreter bug, or at least an undocumented
4047+ # inconsistency.
4048+ return self.__get__(obj)(*args, **kwargs)
4049+
4050+
4051+def patcher_recorder(mocker, event):
4052+ mock = event.path.root_mock
4053+ if mock.__mocker_patcher__ and len(event.path.actions) == 1:
4054+ patcher = mock.__mocker_patcher__
4055+ patcher.monitor(mock.__mocker_object__, event.path.actions[0].kind)
4056+
4057+Mocker.add_recorder(patcher_recorder)
4058
4059=== added directory 'data'
4060=== added file 'data/couchdb.tmpl'
4061--- data/couchdb.tmpl 1970-01-01 00:00:00 +0000
4062+++ data/couchdb.tmpl 2009-08-20 12:55:54 +0000
4063@@ -0,0 +1,38 @@
4064+<!doctype html>
4065+<html>
4066+<head>
4067+<title>Your Desktop CouchDB</title>
4068+<script>
4069+window.onload = function() {
4070+ if (document.cookie == "yes") {
4071+ location.href = document.getElementById("there").href;
4072+ }
4073+ document.getElementById("there").addEventListener("click", function(e) {
4074+ document.cookie = "yes; expires=Thu, 31 Dec 2099 21:00:00 UTC";
4075+ }, false);
4076+ var count = 30;
4077+ setInterval(function() {
4078+ count -= 1;
4079+ if (count < 0) {
4080+ location.href = document.getElementById("there").href;
4081+ return;
4082+ }
4083+ document.getElementsByTagName("span")[0].innerHTML = count;
4084+ }, 1000);
4085+}
4086+</script>
4087+</head>
4088+<body>
4089+<h1>Desktop CouchDB</h1>
4090+<p>Your desktop CouchDB is the data store for many of your applications.
4091+You can browse around it to see which data your applications are storing.</p>
4092+<p>You should bookmark this page (by going to <strong>Bookmarks > Bookmark
4093+This Page</strong> or pressing <strong>Ctrl-D</strong>) so you can easily
4094+come back to browse your CouchDB again.</p>
4095+<p>Don't bookmark the CouchDB page itself, because its location may change!</p>
4096+<p>Taking you to your Desktop CouchDB in <span>30</span> seconds...
4097+<a id="there" href="http://[[COUCHDB_USERNAME]]:[[COUCHDB_PASSWORD]]@localhost:[[COUCHDB_PORT]]/_utils">take me
4098+there straight away from now on</a> (remember to bookmark this page first!)</p>
4099+</body>
4100+</html>
4101+
4102
4103=== added directory 'debian'
4104=== added file 'debian/changelog'
4105--- debian/changelog 1970-01-01 00:00:00 +0000
4106+++ debian/changelog 2009-09-01 21:50:36 +0000
4107@@ -0,0 +1,81 @@
4108+desktopcouch (0.3.1-0ubuntu1) karmic; urgency=low
4109+
4110+ [Ken VanDine]
4111+ * debian/control
4112+ - Added depends on python-desktopcouch-records. (LP: #422179)
4113+ [Chad Miller]
4114+ * New upstream release.
4115+ * Changed Vcs-Bzr links in control file.
4116+ * Changed version dependency on couchdb.
4117+ * Converting to a full-blown source-package branch.
4118+ * Fix getPort failure. (LP: #420911, LP: #422127)
4119+ * Check couchdb bind-port in replicator. (LP: #419973)
4120+ * Change couchdb bind-port in pairing tool. (LP: #419969)
4121+
4122+ -- Chad Miller <chad.miller@canonical.com> Tue, 01 Sep 2009 11:57:25 -0400
4123+
4124+desktopcouch (0.3-0ubuntu1) karmic; urgency=low
4125+
4126+ [ Ken VanDine ]
4127+ * New upstream release (LP: #416591)
4128+ - added unit tests for couchwidget, and then fixed bug #412266
4129+ - Change to freedesktop URL for record type spec.
4130+ - First version of the contacts picker, based on CouchWidget
4131+ - Adding the desktopcouch.contacts module.
4132+ - Use subprocess.Popen and ourselves to the wait()ing,
4133+ since subprocess.call() is buggy. There's still an EINTR bug
4134+ in subprocess, though.
4135+ - Occasionally stop couchdb in tests, so we exercise the automatic
4136+ starting code. This will lead to spurious errors because of the
4137+ aforementioned subprocess bug, but it's the right thing to do.
4138+ - Abstract away some of the linuxisms and complain if we're run on
4139+ an unsupported OS.
4140+ - Fix a race condition in the process-testing code.
4141+ - Replace the TestCase module with one that doesn't complain of dirty
4142+ twisted reactors.
4143+ - Add a means of stopping the desktop couchdb daemon.
4144+ - Add an additional check that a found PID and process named correctly
4145+ is indeed a process that this user started, so we don't try to talk
4146+ to other local users' desktop couchdbs.
4147+ - Get the port at function-call time, instead of storing a port at
4148+ start-time and giving that back. The info can be stale, the old
4149+ way.
4150+ - Don't create a view per record-type; instead, call the standard
4151+ return-all-records-keyed-by-record-type and use slice notation on
4152+ the viewresults to only get back the records with that type,
4153+ which does the same thing but more elegantly.
4154+ - Remove the unused/invalid "utils" import from test_server
4155+ - Change the name of a function tested to be what actually exists in
4156+ the code.
4157+ - Refactored server.py by renaming server.get_records_and_type to
4158+ server.get_records. Also modified the function to take a record
4159+ type param if desired to only create records of that type and
4160+ optionally create a view name "get_"+ record_type. (LP: #411475)
4161+ * debian/control
4162+ - Make python-desktopcouch depend on python-gtk2 and python-gnomekeyring
4163+ - Make python-desktopcouch-records depend on python-gtk2,
4164+ python-gnomekeyring, and python-oauth.
4165+ - Remove depends for python-distutils-extra
4166+ - Fixed Vcs-Browser tag
4167+
4168+ [Elliot Murphy]
4169+ * debian/control: added build-dep on python-setuptools
4170+
4171+
4172+ [ Martin Pitt ]
4173+ * debian/control: Fix Vcs-* links.
4174+
4175+ -- Ken VanDine <ken.vandine@canonical.com> Thu, 27 Aug 2009 15:32:11 +0200
4176+
4177+desktopcouch (0.2-0ubuntu1) karmic; urgency=low
4178+
4179+ * New upstream release
4180+ * Handle the case where the pid file is empty or doesn't exist (LP: #408796)
4181+
4182+ -- Ken VanDine <ken.vandine@canonical.com> Wed, 05 Aug 2009 02:17:47 +0100
4183+
4184+desktopcouch (0.1-0ubuntu1) karmic; urgency=low
4185+
4186+ * Initial release (LP: #397662)
4187+
4188+ -- Ken VanDine <ken.vandine@canonical.com> Fri, 31 Jul 2009 13:44:45 -0400
4189
4190=== added file 'debian/compat'
4191--- debian/compat 1970-01-01 00:00:00 +0000
4192+++ debian/compat 2009-09-01 15:46:56 +0000
4193@@ -0,0 +1,1 @@
4194+6
4195
4196=== added file 'debian/control'
4197--- debian/control 1970-01-01 00:00:00 +0000
4198+++ debian/control 2009-09-01 16:00:58 +0000
4199@@ -0,0 +1,75 @@
4200+Source: desktopcouch
4201+Section: python
4202+Priority: optional
4203+Build-Depends: cdbs (>= 0.4.43),
4204+ debhelper (>= 6),
4205+ python,
4206+ python-central (>= 0.6.11),
4207+ python-distutils-extra (>= 2.8),
4208+ python-setuptools
4209+Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
4210+Standards-Version: 3.8.2
4211+XS-Python-Version: current
4212+Homepage: http://launchpad.net/desktopcouch
4213+Vcs-Bzr: https://code.launchpad.net/~ubuntuone-control-tower/ubuntu/karmic/desktopcouch/spb
4214+Vcs-Browser: http://bazaar.launchpad.net/~ubuntuone-control-tower/ubuntu/karmic/desktopcouch/spb
4215+
4216+Package: desktopcouch
4217+Architecture: all
4218+XB-Python-Version: ${python:Versions}
4219+Depends: ${misc:Depends},
4220+ ${python:Depends},
4221+ couchdb (>= 0.10.0~svn809550),
4222+ python-dbus,
4223+ python-couchdb (>= 0.6),
4224+ python-twisted-core,
4225+ python-gobject,
4226+ python-avahi,
4227+ python-desktopcouch,
4228+ python-desktopcouch-records,
4229+ python-gtk2
4230+Description: A Desktop CouchDB instance
4231+ Runs an instance of CouchDB with the users session.
4232+
4233+Package: desktopcouch-tools
4234+Architecture: all
4235+XB-Python-Version: ${python:Versions}
4236+Depends: ${misc:Depends},
4237+ ${python:Depends},
4238+ python-dbus,
4239+ python-twisted-core,
4240+ python-gobject,
4241+ python-avahi,
4242+ python-desktopcouch,
4243+ python-gtk2
4244+Description: Desktop CouchDB tools
4245+ Tools used to work with Desktop CouchDB.
4246+
4247+Package: python-desktopcouch
4248+Architecture: all
4249+XB-Python-Version: ${python:Versions}
4250+Depends: ${misc:Depends},
4251+ ${python:Depends},
4252+ desktopcouch,
4253+ python-dbus,
4254+ python-couchdb,
4255+ python-xdg,
4256+ python-twisted-core,
4257+ python-gtk2,
4258+ python-gnomekeyring
4259+Description: Python Desktop CouchDB
4260+ A Python library for Desktop CouchDB.
4261+
4262+Package: python-desktopcouch-records
4263+Architecture: all
4264+XB-Python-Version: ${python:Versions}
4265+Depends: ${misc:Depends},
4266+ ${python:Depends},
4267+ python-dbus,
4268+ python-couchdb,
4269+ python-desktopcouch,
4270+ python-gtk2,
4271+ python-gnomekeyring,
4272+ python-oauth
4273+Description: Desktop CouchDB Records API
4274+ A Python library for the Desktop CouchDB Records API.
4275
4276=== added file 'debian/copyright'
4277--- debian/copyright 1970-01-01 00:00:00 +0000
4278+++ debian/copyright 2009-09-01 15:46:56 +0000
4279@@ -0,0 +1,11 @@
4280+Format-Specification: http://wiki.debian.org/Proposals/CopyrightFormat
4281+Upstream-Name: desktopcouch
4282+Upstream-Maintainer: Stuart Langridge <stuart.langridge@canonical.com>
4283+Upstream-Source: https://launchpad.net/desktopcouch
4284+
4285+Files: *
4286+Copyright: (C) 2009 Canonical Ltd.
4287+
4288+License: LGPL-3
4289+ The full text of the LGPL is distributed in
4290+ /usr/share/common-licenses/LGPL-3 on Debian systems.
4291
4292=== added file 'debian/desktopcouch-tools.install'
4293--- debian/desktopcouch-tools.install 1970-01-01 00:00:00 +0000
4294+++ debian/desktopcouch-tools.install 2009-09-01 15:46:56 +0000
4295@@ -0,0 +1,4 @@
4296+debian/tmp/usr/share/applications/desktopcouch-pair.desktop
4297+debian/tmp/usr/bin/desktopcouch-pair
4298+debian/tmp/usr/share/man/man1/desktopcouch-pair.1
4299+#debian/tmp/usr/share/locale/*/LC_MESSAGES/desktopcouch.mo
4300
4301=== added file 'debian/desktopcouch.install'
4302--- debian/desktopcouch.install 1970-01-01 00:00:00 +0000
4303+++ debian/desktopcouch.install 2009-09-01 15:46:56 +0000
4304@@ -0,0 +1,3 @@
4305+debian/tmp/usr/share/desktopcouch
4306+debian/tmp/usr/lib/desktopcouch/desktopcouch-{stop,service}
4307+debian/tmp/usr/share/dbus-1/services/org.desktopcouch.CouchDB.service
4308
4309=== added file 'debian/pycompat'
4310--- debian/pycompat 1970-01-01 00:00:00 +0000
4311+++ debian/pycompat 2009-09-01 15:46:56 +0000
4312@@ -0,0 +1,1 @@
4313+2
4314
4315=== added file 'debian/python-desktopcouch-records.install'
4316--- debian/python-desktopcouch-records.install 1970-01-01 00:00:00 +0000
4317+++ debian/python-desktopcouch-records.install 2009-09-01 15:46:56 +0000
4318@@ -0,0 +1,2 @@
4319+debian/tmp/usr/share/doc/python-desktopcouch-records/api
4320+debian/tmp/usr/lib/*/*/desktopcouch/records/*
4321
4322=== added file 'debian/python-desktopcouch.install'
4323--- debian/python-desktopcouch.install 1970-01-01 00:00:00 +0000
4324+++ debian/python-desktopcouch.install 2009-09-01 15:46:56 +0000
4325@@ -0,0 +1,2 @@
4326+debian/tmp/usr/lib/*/*/desktopcouch/*.py
4327+debian/tmp/usr/lib/*/*/desktopcouch/pair/{couchdb_pairing,__init__.py}
4328
4329=== added file 'debian/rules'
4330--- debian/rules 1970-01-01 00:00:00 +0000
4331+++ debian/rules 2009-09-01 15:46:56 +0000
4332@@ -0,0 +1,7 @@
4333+#!/usr/bin/make -f
4334+
4335+DEB_PYTHON_SYSTEM := pycentral
4336+
4337+include /usr/share/cdbs/1/rules/debhelper.mk
4338+include /usr/share/cdbs/1/class/python-distutils.mk
4339+include /usr/share/cdbs/1/rules/langpack.mk
4340
4341=== added file 'debian/watch'
4342--- debian/watch 1970-01-01 00:00:00 +0000
4343+++ debian/watch 2009-09-01 15:46:56 +0000
4344@@ -0,0 +1,2 @@
4345+version=3
4346+http://launchpad.net/desktopcouch/+download .*/desktopcouch-([0-9.]+)\.tar\.gz
4347
4348=== added directory 'desktopcouch'
4349=== added file 'desktopcouch-pair.desktop.in'
4350--- desktopcouch-pair.desktop.in 1970-01-01 00:00:00 +0000
4351+++ desktopcouch-pair.desktop.in 2009-07-27 19:18:55 +0000
4352@@ -0,0 +1,8 @@
4353+[Desktop Entry]
4354+_Name=CouchDB Pairing Tool
4355+Type=Application
4356+_Comment=Utility for pairing Desktop CouchDB
4357+Exec=desktopcouch-pair
4358+Icon=
4359+Categories=Network;
4360+_GenericName=CouchDB Pairing Tool
4361
4362=== added file 'desktopcouch/__init__.py'
4363--- desktopcouch/__init__.py 1970-01-01 00:00:00 +0000
4364+++ desktopcouch/__init__.py 2009-09-01 00:38:53 +0000
4365@@ -0,0 +1,98 @@
4366+# Copyright 2009 Canonical Ltd.
4367+#
4368+# This file is part of desktopcouch.
4369+#
4370+# desktopcouch is free software: you can redistribute it and/or modify
4371+# it under the terms of the GNU Lesser General Public License version 3
4372+# as published by the Free Software Foundation.
4373+#
4374+# desktopcouch is distributed in the hope that it will be useful,
4375+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4376+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4377+# GNU Lesser General Public License for more details.
4378+#
4379+# You should have received a copy of the GNU Lesser General Public License
4380+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4381+"Desktop Couch helper files"
4382+
4383+from __future__ import with_statement
4384+import os, re, time
4385+from desktopcouch.start_local_couchdb import process_is_couchdb, read_pidfile
4386+
4387+def find_pid(start_if_not_running=True):
4388+ # Work out whether CouchDB is running by looking at its pid file
4389+ pid = read_pidfile()
4390+ if not process_is_couchdb(pid) and start_if_not_running:
4391+ # start CouchDB by running the startup script
4392+ print "Desktop CouchDB is not running; starting it.",
4393+ from desktopcouch import start_local_couchdb
4394+ pid = start_local_couchdb.start_couchdb()
4395+ # now load the design documents, because it's started
4396+ start_local_couchdb.update_design_documents()
4397+
4398+ if not process_is_couchdb(pid):
4399+ raise RuntimeError("desktop-couch not started")
4400+
4401+ return pid
4402+
4403+def find_port__linux(pid=None):
4404+ if pid is None:
4405+ pid = find_pid()
4406+
4407+ proc_dir = "/proc/%s" % (pid,)
4408+
4409+ # enumerate the process' file descriptors
4410+ fd_dir = os.path.join(proc_dir, 'fd')
4411+ try:
4412+ fd_paths = [os.readlink(os.path.join(fd_dir, fd))
4413+ for fd in os.listdir(fd_dir)]
4414+ except OSError:
4415+ raise RuntimeError("Unable to find file descriptors in /proc")
4416+
4417+ # identify socket fds
4418+ socket_matches = [re.match('socket:\\[([0-9]+)\\]', p) for p in fd_paths]
4419+ # extract their inode numbers
4420+ socket_inodes = [m.group(1) for m in socket_matches if m is not None]
4421+
4422+ # construct a subexpression which matches any one of these inodes
4423+ inode_subexp = "|".join(map(re.escape, socket_inodes))
4424+ # construct regexp to match /proc/net/tcp entries which are listening
4425+ # sockets having one of the given inode numbers
4426+ listening_regexp = re.compile(r'''
4427+ \s*\d+:\s* # sl
4428+ [0-9A-F]{8}: # local_address part 1
4429+ ([0-9A-F]{4})\s+ # local_address part 2
4430+ 00000000:0000\s+ # rem_address
4431+ 0A\s+ # st (0A = listening)
4432+ [0-9A-F]{8}: # tx_queue
4433+ [0-9A-F]{8}\s+ # rx_queue
4434+ [0-9A-F]{2}: # tr
4435+ [0-9A-F]{8}\s+ # tm->when
4436+ [0-9A-F]{8}\s* # retrnsmt
4437+ \d+\s+\d+\s+ # uid, timeout
4438+ (?:%s)\s+ # inode
4439+ ''' % (inode_subexp,), re.VERBOSE)
4440+
4441+ # extract the TCP port from the first matching line in /proc/$pid/net/tcp
4442+ port = None
4443+ with open(os.path.join(proc_dir, 'net', 'tcp')) as tcp_file:
4444+ for line in tcp_file:
4445+ match = listening_regexp.match(line)
4446+ if match is not None:
4447+ port = str(int(match.group(1), 16))
4448+ break
4449+ if port is None:
4450+ raise RuntimeError("Unable to find listening port")
4451+
4452+ return port
4453+
4454+
4455+
4456+import platform
4457+os_name = platform.system()
4458+try:
4459+ find_port = {
4460+ "Linux": find_port__linux
4461+ } [os_name]
4462+except KeyError:
4463+ raise NotImplementedError("os %r is not yet supported" % (os_name,))
4464
4465=== added directory 'desktopcouch/contacts'
4466=== added file 'desktopcouch/contacts/__init__.py'
4467--- desktopcouch/contacts/__init__.py 1970-01-01 00:00:00 +0000
4468+++ desktopcouch/contacts/__init__.py 2009-08-17 21:39:48 +0000
4469@@ -0,0 +1,20 @@
4470+# Copyright 2009 Canonical Ltd.
4471+#
4472+# This file is part of desktopcouch-contacts.
4473+#
4474+# desktopcouch is free software: you can redistribute it and/or modify
4475+# it under the terms of the GNU Lesser General Public License version 3
4476+# as published by the Free Software Foundation.
4477+#
4478+# desktopcouch is distributed in the hope that it will be useful,
4479+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4480+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4481+# GNU Lesser General Public License for more details.
4482+#
4483+# You should have received a copy of the GNU Lesser General Public License
4484+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4485+#
4486+# Authors: Eric Casteleijn <eric.casteleijn@canonical.com>
4487+# Nicola Larosa <nicola.larosa@canonical.com>
4488+
4489+"""UbuntuOne Contacts API"""
4490
4491=== added file 'desktopcouch/contacts/contactspicker.py'
4492--- desktopcouch/contacts/contactspicker.py 1970-01-01 00:00:00 +0000
4493+++ desktopcouch/contacts/contactspicker.py 2009-08-24 20:35:25 +0000
4494@@ -0,0 +1,81 @@
4495+# Copyright 2009 Canonical Ltd.
4496+#
4497+# This file is part of desktopcouch-contacts.
4498+#
4499+# desktopcouch is free software: you can redistribute it and/or modify
4500+# it under the terms of the GNU Lesser General Public License version 3
4501+# as published by the Free Software Foundation.
4502+#
4503+# desktopcouch is distributed in the hope that it will be useful,
4504+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4505+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4506+# GNU Lesser General Public License for more details.
4507+#
4508+# You should have received a copy of the GNU Lesser General Public License
4509+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4510+#
4511+# Authors: Rodrigo Moya <rodrigo.moya@canonical.com
4512+
4513+"""A widget to allow users to pick contacts"""
4514+
4515+import gtk
4516+from desktopcouch.contacts.record import CONTACT_RECORD_TYPE
4517+from desktopcouch.records.couchgrid import CouchGrid
4518+
4519+
4520+class ContactsPicker(gtk.VBox):
4521+ """A contacts picker"""
4522+
4523+ def __init__(self, uri=None):
4524+ """Create a new ContactsPicker widget."""
4525+
4526+ gtk.VBox.__init__(self)
4527+
4528+ # Create search entry and button
4529+ hbox = gtk.HBox()
4530+ self.pack_start(hbox, False, False, 3)
4531+
4532+ self.search_entry = gtk.Entry()
4533+ hbox.pack_start(self.search_entry, True, True, 3)
4534+
4535+ self.search_button = gtk.Button(
4536+ stock=gtk.STOCK_FIND, use_underline=True)
4537+ hbox.pack_start(self.search_button, False, False, 3)
4538+
4539+ # Create CouchGrid to contain list of contacts
4540+ self.contacts_list = CouchGrid('contacts', uri=uri)
4541+ self.contacts_list.editable = False
4542+ self.contacts_list.keys = [ "first_name", "last_name" ]
4543+ self.contacts_list.record_type = CONTACT_RECORD_TYPE
4544+
4545+ #Pimp out the columns with some nicer titles
4546+ #TODO: this should be set up for translatability
4547+ columns = self.contacts_list.get_columns()
4548+ columns[0].set_title("First Name")
4549+ columns[1].set_title("Last Name")
4550+
4551+ self.contacts_list.show()
4552+ self.pack_start(self.contacts_list, True, True, 3)
4553+
4554+ def get_contacts_list(self):
4555+ """get_contacts_list - gtk.Widget value
4556+ Gets the CouchGrid inside the ContactsPicker widget
4557+ """
4558+ return self.contacts_list
4559+
4560+if __name__ == "__main__":
4561+ """creates a test ContactsPicker if called directly"""
4562+
4563+ # Create and show a test window
4564+ win = gtk.Dialog("ContactsPicker widget test", None, 0,
4565+ (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE))
4566+ win.connect("response", gtk.main_quit)
4567+ win.resize(300, 450)
4568+
4569+ # Create the contacts picker widget
4570+ picker = ContactsPicker()
4571+ win.get_content_area().pack_start(picker, True, True, 3)
4572+
4573+ # Run the test application
4574+ win.show_all()
4575+ gtk.main()
4576
4577=== added file 'desktopcouch/contacts/record.py'
4578--- desktopcouch/contacts/record.py 1970-01-01 00:00:00 +0000
4579+++ desktopcouch/contacts/record.py 2009-08-19 10:07:54 +0000
4580@@ -0,0 +1,34 @@
4581+# Copyright 2009 Canonical Ltd.
4582+#
4583+# This file is part of desktopcouch-contacts.
4584+#
4585+# desktopcouch is free software: you can redistribute it and/or modify
4586+# it under the terms of the GNU Lesser General Public License version 3
4587+# as published by the Free Software Foundation.
4588+#
4589+# desktopcouch is distributed in the hope that it will be useful,
4590+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4591+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4592+# GNU Lesser General Public License for more details.
4593+#
4594+# You should have received a copy of the GNU Lesser General Public License
4595+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4596+#
4597+# Authors: Eric Casteleijn <eric.casteleijn@canonical.com>
4598+# Nicola Larosa <nicola.larosa@canonical.com>
4599+# Mark G. Saye <mark.saye@canonical.com>
4600+
4601+
4602+"""A dictionary based contact record representation."""
4603+
4604+from desktopcouch.records.record import Record
4605+
4606+CONTACT_RECORD_TYPE = 'http://www.freedesktop.org/wiki/Specifications/desktopcouch/contact'
4607+
4608+
4609+class Contact(Record):
4610+ """An Ubuntuone Contact Record."""
4611+
4612+ def __init__(self, data=None, record_id=None):
4613+ super(Contact, self).__init__(
4614+ record_id=record_id, data=data, record_type=CONTACT_RECORD_TYPE)
4615
4616=== added file 'desktopcouch/contacts/schema.txt'
4617--- desktopcouch/contacts/schema.txt 1970-01-01 00:00:00 +0000
4618+++ desktopcouch/contacts/schema.txt 2009-08-19 10:07:54 +0000
4619@@ -0,0 +1,50 @@
4620+# Copyright 2009 Canonical Ltd.
4621+#
4622+# This file is part of desktopcouch-contacts.
4623+#
4624+# desktopcouch is free software: you can redistribute it and/or modify
4625+# it under the terms of the GNU Lesser General Public License version 3
4626+# as published by the Free Software Foundation.
4627+#
4628+# desktopcouch is distributed in the hope that it will be useful,
4629+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4630+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4631+# GNU Lesser General Public License for more details.
4632+#
4633+# You should have received a copy of the GNU Lesser General Public License
4634+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4635+
4636+Schema
4637+
4638+The proposed CouchDB contact schema is as follows:
4639+
4640+Core fields
4641+
4642+ * record_type 'http://www.freedesktop.org/wiki/Specifications/desktopcouch/contact'
4643+ * first_name (string)
4644+ * last_name (string)
4645+ * birth_date (string, "YYYY-MM-DD")
4646+ * addresses (MergeableList of "address" dictionaries)
4647+ o city (string)
4648+ o address1 (string)
4649+ o address2 (string)
4650+ o pobox (string)
4651+ o state (string)
4652+ o country (string)
4653+ o postalcode (string)
4654+ o description (string, e.g., "Home")
4655+ * email_addresses (MergeableList of "emailaddress" dictionaries)
4656+ o address (string),
4657+ o description (string)
4658+ * phone_numbers (MergeableList of "phone number" dictionaries)
4659+ o number (string)
4660+ o description (string)
4661+ * application_annotations Everything else, organized per application.
4662+
4663+Note: None of the core fields are mandatory, but applications should
4664+not add any other fields at the top level of the record. Any fields
4665+needed not defined here should be put under application_annotations in
4666+the namespace of the application there. So for Ubuntu One:
4667+
4668+ "application_annotations": {
4669+ "Ubuntu One": {<Ubuntu One specific fields here>}}
4670
4671=== added directory 'desktopcouch/contacts/testing'
4672=== added file 'desktopcouch/contacts/testing/__init__.py'
4673--- desktopcouch/contacts/testing/__init__.py 1970-01-01 00:00:00 +0000
4674+++ desktopcouch/contacts/testing/__init__.py 2009-08-17 21:39:48 +0000
4675@@ -0,0 +1,20 @@
4676+# Copyright 2009 Canonical Ltd.
4677+#
4678+# This file is part of desktopcouch-contacts.
4679+#
4680+# desktopcouch is free software: you can redistribute it and/or modify
4681+# it under the terms of the GNU Lesser General Public License version 3
4682+# as published by the Free Software Foundation.
4683+#
4684+# desktopcouch is distributed in the hope that it will be useful,
4685+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4686+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4687+# GNU Lesser General Public License for more details.
4688+#
4689+# You should have received a copy of the GNU Lesser General Public License
4690+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4691+#
4692+# Authors: Stuart Langridge <stuart.langridge@canonical.com>
4693+# Nicola Larosa <nicola.larosa@canonical.com>
4694+
4695+"""Support code for tests"""
4696
4697=== added file 'desktopcouch/contacts/testing/create.py'
4698--- desktopcouch/contacts/testing/create.py 1970-01-01 00:00:00 +0000
4699+++ desktopcouch/contacts/testing/create.py 2009-08-19 10:07:54 +0000
4700@@ -0,0 +1,113 @@
4701+# Copyright 2009 Canonical Ltd.
4702+#
4703+# This file is part of desktopcouch-contacts.
4704+#
4705+# desktopcouch is free software: you can redistribute it and/or modify
4706+# it under the terms of the GNU Lesser General Public License version 3
4707+# as published by the Free Software Foundation.
4708+#
4709+# desktopcouch is distributed in the hope that it will be useful,
4710+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4711+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4712+# GNU Lesser General Public License for more details.
4713+#
4714+# You should have received a copy of the GNU Lesser General Public License
4715+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4716+#
4717+# Authors: Stuart Langridge <stuart.langridge@canonical.com>
4718+# Nicola Larosa <nicola.larosa@canonical.com>
4719+
4720+"""Creating CouchDb-stored contacts for testing"""
4721+
4722+import random, string, uuid
4723+
4724+from couchdb import Server
4725+
4726+CONTACT_DOCTYPE = 'http://www.freedesktop.org/wiki/Specifications/desktopcouch/contact'
4727+COUCHDB_SYS_PORT = 5984
4728+
4729+FIRST_NAMES = ('Jack', 'Thomas', 'Oliver', 'Joshua', 'Harry', 'Charlie',
4730+ 'Daniel', 'William', 'James', 'Alfie', 'Grace', 'Ruby', 'Olivia',
4731+ 'Emily', 'Jessica', 'Sophie', 'Chloe', 'Lily', 'Ella', 'Amelia')
4732+LAST_NAMES = ('Dalglish', 'Grobbelaar', 'Lawrenson', 'Beglin', 'Nicol',
4733+ 'Whelan', 'Hansen', 'Johnston', 'Rush', 'Molby', 'MacDonald', 'McMahon')
4734+CITIES = ('Scunthorpe', 'Birmingham', 'Cambridge', 'Durham', 'Bedford')
4735+COUNTRIES = ('England', 'Ireland', 'Scotland', 'Wales')
4736+
4737+def random_string(length=10):
4738+ """Return a string of random lowercase letters and of specified length"""
4739+ return ''.join(random.sample(string.lowercase, length))
4740+
4741+def random_postal_address():
4742+ """Return something that looks like a postal address"""
4743+ return '%s Street' % random.choice(LAST_NAMES)
4744+
4745+def random_email_address(first_name, last_name):
4746+ """Return something that looks like an email address"""
4747+ return '%s.%s@%s.com' % (first_name, last_name, random_string(3))
4748+
4749+def random_postal_code():
4750+ """Return something that looks like a postal code"""
4751+ return '%s12 3%s' % (random_string(2), random_string(2))
4752+
4753+def random_phone_number():
4754+ """Return something that looks like a phone number"""
4755+ return '+%s %s %s %s' % (random.randint(10, 99), random.randint(10, 99),
4756+ random.randint(1000, 9999), random.randint(1000, 9999))
4757+
4758+def random_birth_date():
4759+ """Return something that looks like a birth date"""
4760+ return '%04d-%02d-%02d' % (random.randint(1900, 2006),
4761+ random.randint(1, 12), random.randint(1, 28))
4762+
4763+def make_one_contact(maincount, doctype, app_annots):
4764+ """Make up one contact randomly"""
4765+ # Record schema
4766+ fielddict = {'record_type': doctype, 'record_type_version': '1.0'}
4767+ # Names
4768+ first_name = random.choice(FIRST_NAMES) + str(maincount)
4769+ last_name = random.choice(LAST_NAMES)
4770+ # Addresses
4771+ addresses = {}
4772+ for address_type in ('home', 'work', 'other'):
4773+ addresses[str(uuid.uuid4())] = {
4774+ 'address1': random_postal_address(), 'address2': '',
4775+ 'pobox': '', 'city': random.choice(CITIES),
4776+ 'state': '', 'postalcode': random_postal_code(),
4777+ 'country': random.choice(COUNTRIES), 'description': address_type}
4778+ # Email addresses
4779+ email_addresses = {}
4780+ for email_address_type in ('home', 'work', 'other'):
4781+ email_addresses[str(uuid.uuid4())] = {
4782+ 'address': random_email_address(first_name, last_name),
4783+ 'description': email_address_type}
4784+ # Phone numbers
4785+ phone_numbers = {}
4786+ for phone_number_type in ('home', 'work', 'other'):
4787+ phone_numbers[str(uuid.uuid4())] = {
4788+ 'priority': 0, 'number': random_phone_number(),
4789+ 'description': phone_number_type}
4790+ # Store data in fielddict
4791+ fielddict.update({'first_name': first_name, 'last_name': last_name,
4792+ 'addresses': addresses, 'email_addresses': email_addresses,
4793+ 'phone_numbers': phone_numbers, 'birth_date': random_birth_date()})
4794+ # Possibly add example application annotations
4795+ if app_annots:
4796+ fielddict['application_annotations'] = app_annots
4797+ return fielddict
4798+
4799+def create_many_contacts(
4800+ num_contacts=10, host='localhost', port=COUCHDB_SYS_PORT,
4801+ db_name='contacts', doctype=CONTACT_DOCTYPE, app_annots=None):
4802+ """Make many contacts and create their records"""
4803+ server_url = 'http://%s:%s/' % (host, port)
4804+ server = Server(server_url)
4805+ db = server[db_name] if db_name in server else server.create(db_name)
4806+ record_ids = []
4807+ for maincount in range(1, num_contacts + 1):
4808+ # Make the contact
4809+ fielddict = make_one_contact(maincount, doctype, app_annots)
4810+ # Store data in CouchDB
4811+ record_id = db.create(fielddict)
4812+ record_ids.append(record_id)
4813+ return record_ids
4814
4815=== added directory 'desktopcouch/contacts/tests'
4816=== added file 'desktopcouch/contacts/tests/__init__.py'
4817--- desktopcouch/contacts/tests/__init__.py 1970-01-01 00:00:00 +0000
4818+++ desktopcouch/contacts/tests/__init__.py 2009-08-17 21:39:48 +0000
4819@@ -0,0 +1,17 @@
4820+# Copyright 2009 Canonical Ltd.
4821+#
4822+# This file is part of desktopcouch-contacts.
4823+#
4824+# desktopcouch is free software: you can redistribute it and/or modify
4825+# it under the terms of the GNU Lesser General Public License version 3
4826+# as published by the Free Software Foundation.
4827+#
4828+# desktopcouch is distributed in the hope that it will be useful,
4829+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4830+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4831+# GNU Lesser General Public License for more details.
4832+#
4833+# You should have received a copy of the GNU Lesser General Public License
4834+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4835+
4836+"Tests for Contacts API"
4837
4838=== added file 'desktopcouch/contacts/tests/test_contactspicker.py'
4839--- desktopcouch/contacts/tests/test_contactspicker.py 1970-01-01 00:00:00 +0000
4840+++ desktopcouch/contacts/tests/test_contactspicker.py 2009-08-24 20:35:25 +0000
4841@@ -0,0 +1,55 @@
4842+# Copyright 2009 Canonical Ltd.
4843+#
4844+# This file is part of desktopcouch-contacts.
4845+#
4846+# desktopcouch is free software: you can redistribute it and/or modify
4847+# it under the terms of the GNU Lesser General Public License version 3
4848+# as published by the Free Software Foundation.
4849+#
4850+# desktopcouch is distributed in the hope that it will be useful,
4851+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4852+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4853+# GNU Lesser General Public License for more details.
4854+#
4855+# You should have received a copy of the GNU Lesser General Public License
4856+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4857+#
4858+# Authors: Rick Spencer <rick.spencer@canonical.com>
4859+
4860+"""Tests for the ContactsPicker class"""
4861+
4862+import testtools
4863+import gtk
4864+from desktopcouch.contacts.contactspicker import ContactsPicker
4865+from desktopcouch.records.server import CouchDatabase
4866+from desktopcouch.records.tests import get_uri
4867+
4868+URI = get_uri()
4869+
4870+class TestContactsPicker(testtools.TestCase):
4871+ """Test the Contact Picker Window."""
4872+
4873+ def setUp(self):
4874+ """setup each test"""
4875+ # Connect to CouchDB server
4876+ self.dbname = 'contacts'
4877+ self.database = CouchDatabase(self.dbname, create=True, uri=URI)
4878+
4879+ def tearDown(self):
4880+ """tear down each test"""
4881+ del self.database._server[self.dbname]
4882+
4883+ def test_can_contruct_contactspicker(self):
4884+ """Test that we can build the window"""
4885+ # Create and show a test window
4886+ win = gtk.Dialog("ContactsPicker widget test", None, 0,
4887+ (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE))
4888+ win.connect("response", gtk.main_quit)
4889+ win.resize(300, 450)
4890+
4891+ # Create the contacts picker widget
4892+ picker = ContactsPicker(uri=URI)
4893+ win.get_content_area().pack_start(picker, True, True, 3)
4894+ self.assert_(picker.get_contacts_list())
4895+
4896+
4897
4898=== added file 'desktopcouch/contacts/tests/test_record.py'
4899--- desktopcouch/contacts/tests/test_record.py 1970-01-01 00:00:00 +0000
4900+++ desktopcouch/contacts/tests/test_record.py 2009-08-17 21:39:48 +0000
4901@@ -0,0 +1,31 @@
4902+# Copyright 2009 Canonical Ltd.
4903+#
4904+# This file is part of desktopcouch-contacts.
4905+#
4906+# desktopcouch is free software: you can redistribute it and/or modify
4907+# it under the terms of the GNU Lesser General Public License version 3
4908+# as published by the Free Software Foundation.
4909+#
4910+# desktopcouch is distributed in the hope that it will be useful,
4911+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4912+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4913+# GNU Lesser General Public License for more details.
4914+#
4915+# You should have received a copy of the GNU Lesser General Public License
4916+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4917+#
4918+# Authors: Nicola Larosa <nicola.larosa@canonical.com>
4919+
4920+"""Tests for the ContactDocument class"""
4921+
4922+import testtools
4923+from desktopcouch.contacts.record import Contact, CONTACT_RECORD_TYPE
4924+
4925+class TestContactRecord(testtools.TestCase):
4926+ """Test the Contact Record object."""
4927+
4928+ def test_contact_record(self):
4929+ """Test that we get the correct record type."""
4930+ contact = Contact()
4931+ self.assertEqual(CONTACT_RECORD_TYPE, contact.record_type)
4932+
4933
4934=== added file 'desktopcouch/local_files.py'
4935--- desktopcouch/local_files.py 1970-01-01 00:00:00 +0000
4936+++ desktopcouch/local_files.py 2009-08-31 15:27:31 +0000
4937@@ -0,0 +1,137 @@
4938+#!/usr/bin/python
4939+# Copyright 2009 Canonical Ltd.
4940+#
4941+# This file is part of desktopcouch.
4942+#
4943+# desktopcouch is free software: you can redistribute it and/or modify
4944+# it under the terms of the GNU Lesser General Public License version 3
4945+# as published by the Free Software Foundation.
4946+#
4947+# desktopcouch is distributed in the hope that it will be useful,
4948+# but WITHOUT ANY WARRANTY; without even the implied warranty of
4949+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4950+# GNU Lesser General Public License for more details.
4951+#
4952+# You should have received a copy of the GNU Lesser General Public License
4953+# along with desktopcouch. If not, see <http://www.gnu.org/licenses/>.
4954+#
4955+# Author: Stuart Langridge <stuart.langridge@canonical.com>
4956+# Eric Casteleijn <eric.casteleijn@canonical.com>
4957+
4958+"""Specify location of files relevant to desktop CouchDB.
4959+
4960+Checks to see whether we're running out of the source tree or not.
4961+"""
4962+
4963+import os
4964+import xdg.BaseDirectory
4965+import subprocess
4966+import logging
4967+try:
4968+ import ConfigParser as configparser
4969+except ImportError:
4970+ import configparser
4971+
4972+def mkpath(rootdir, path):
4973+ "Remove .. from paths"
4974+ return os.path.realpath(os.path.join(rootdir, path))
4975+
4976+rootdir = os.path.join(xdg.BaseDirectory.xdg_cache_home, "desktop-couch")
4977+if not os.path.isdir(rootdir):
4978+ os.mkdir(rootdir)
4979+config_dir = xdg.BaseDirectory.save_config_path("desktop-couch")
4980+FILE_INI = os.path.join(config_dir, "desktop-couchdb.ini")
4981+DIR_DB = xdg.BaseDirectory.save_data_path("desktop-couch")
4982+
4983+FILE_PID = mkpath(rootdir, "desktop-couchdb.pid")
4984+FILE_LOG = mkpath(rootdir, "desktop-couchdb.log")
4985+FILE_STDOUT = mkpath(rootdir, "desktop-couchdb.stdout")
4986+FILE_STDERR = mkpath(rootdir, "desktop-couchdb.stderr")
4987+
4988+COUCH_EXE = os.environ.get('COUCHDB')
4989+if not COUCH_EXE:
4990+ for x in os.environ['PATH'].split(':'):
4991+ if os.path.exists(os.path.join(x, 'couchdb')):
4992+ COUCH_EXE = os.path.join(x, 'couchdb')
4993+if not COUCH_EXE:
4994+ raise ImportError("Could not find couchdb")
4995+
4996+def couch_chain_flag():
4997+ process = subprocess.Popen([COUCH_EXE, '-V'], shell=False,
4998+ stdout=subprocess.PIPE)
4999+ line = process.stdout.read().split('\n')[0]
5000+ couchversion = line.split()[-1]
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches