diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 2f78cf5..0000000 --- a/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.pyc - diff --git a/GitHubExporterFAQ.md b/GitHubExporterFAQ.md new file mode 100644 index 0000000..b8c446f --- /dev/null +++ b/GitHubExporterFAQ.md @@ -0,0 +1,105 @@ +If you have a question that isn't answered here, please log an issue in the [issue tracker](https://code.google.com/p/support-tools/issues/list) or [contact Google](mailto:google-code-shutdown@google.com) for assistance. + + + +# Questions # + +## Where did my Google Code wikis go? ## +The wikis of projects exported to GitHub are converted into Markdown and placed in new `wiki` branch in the GitHub project's repo. + +If you would rather use the GitHub wikis feature instead, GitHub user [morgant](https://github.com/morgant/) wrote [a tool](https://github.com/morgant/finishGoogleCodeGitHubWikiMigration) to move the wiki files from the `wiki` branc into the repo's wiki section. +## How can I export private issues? ## +Issues on Google Code can be labeled in such a way that they are private (e.g. those with `Restrict-View-*`). Private issues will be migrated to GitHub as if they were deleted. None of their contents will be migrated. + +If you need to export private issues, you should not use the Google Code Exporter, and instead [manually export](https://code.google.com/p/support-tools/wiki/MigratingToGitHub) your project to GitHub. + +As part of that process, you will use Google Takeout to get a full archive of your projects issues, which includes those marked as restricted. And the [Issue Exporter](https://code.google.com/p/support-tools/wiki/IssueExporterTool) tool will allow you to import them to GitHub. + +## Are all projects available to be exported to GitHub? ## +No. Some projects are blocked from automatic export to GitHub, specifically those that have too many issues (1,000+) or those which have already moved. + +In these situations, you will need to [manually export](https://code.google.com/p/support-tools/wiki/MigratingToGitHub) your project to GitHub. + +## Can I migrate a Google Code repository to a GitHub Organization? ## +No, however you can quickly transfer the repository after the export is complete. + +For more information about transferring a repository on GitHub, see [this document](https://help.github.com/articles/transferring-a-repository/). + +# Post-Export Actions # + +After the project gets migrated to GitHub, sometimes additional clean-up work is necessary. + +## Fixing author information (SVN only) ## + +While Git and Mercurial based projects store the author information as an email address, SVN does not. This can lead to strange situations when the project is on GitHub. Commits by `larry.page@gmail.com` would show up in GitHub as being by `larry.page` after the export. (Since that is how SVN stored the information.) This means that the commits won't get linked to the GitHub user with email address `larry.page@gmail.com`. + +You can fix this however by updating the git repo's author information. + +The process for rewriting git history to change an author's email address is documented on GitHub under [changing author information](https://help.github.com/articles/changing-author-info/). + +## Setting the "Project Moved" Flag ## + +Once a project has been successfully exported to GitHub, you will want to update your project's homepage on Google Code to avoid confusion. + +Some project owners simply update their project homepage's text to indicate it has moved to GitHub. For example [subtext](https://code.google.com/p/subtext/) or [bwapi](https://code.google.com/p/bwapi/). + +Another option is to set the Google Code "project moved" flag. When set, attempts to access the project will take users to an interstitial page indicating the new project location. In the future, the page will automatically redirect to well-known project hosting services such as [github.com](https://github.com). + +To set the "project moved" flag, navigate to your project's advanced admin page, at `https://code.google.com/p//adminAdvanced`. + +Once there, enter the new project home page URL under "project moved". For example: https://github.com/google/kythe. Finally click the "Project Moved" button. + +If you need to "un-move" a project, you can go back to the `/adminAdvanced` page at a later time and click "Publish". This will restore your project to its original state, before the move. + +# Known Issues # + +This section covers a few common errors you might run into. If you encounter any other bugs or unexpected conversion issues, please log issues in the [issue tracker](https://code.google.com/p/support-tools/issues/list). + +## Error "GitHub code import failure: ..." ## + +There are several kinds of GitHub import failures which can arise, such as + + * Error! There was an error pushing commits to GitHub. + * Error! There was an error importing commits. + +This can happen for several reasons, the most common one is that the Google Code repository is too large. + +GitHub will block pushes where a single file is larger than 100MiB. Similarly, the default limit for a GitHub is 1GiB. See [working with large files](https://help.github.com/articles/working-with-large-files/). + +Simply `git rm`-ing a 100+MiB file from your repo is not enough, since the large file will still exist in your repos history. Instead, you need to erase the file from your repo's entirely history. (Literally rewrite history.) GitHub provides documentation for how to do this at [removing sensitive data](https://help.github.com/articles/remove-sensitive-data/). + + +If you do have a consistent error importing your code into GitHub please contact GitHub's support at https://github.com/contact. Please include the name of the target repository (e.g. https://github.com/user/repo), and they will be able to assist you from there. + +## Error "GitHub code import took too long." ## + +If the GitHub import process takes too long the project export is terminated. Please retry your project export, and if the problem persists contact [Google](mailto:google-code-shutdown@google.com) or [GitHub](https://github.com/contact?form%5Bsubject%5D=Google+Code+Export:+Error+code+import+took+too+long). + +## Error "Project cannot be migrated because it has too many issues." ## +There is a hard limit on the number of issues that can be exported by the tool, per repo. If your project has more than 1,000 issues the export will fail. + +To migrate your issues repos, you will need to use the stand-alone [Issue Exporter](https://code.google.com/p/support-tools/wiki/IssueExporterTool). + +## Error "Error migrating issues." ## + +There was an error migrating your projects issues. You can try re-exporting your project in GitHub (deleting the repo, and then using the Exporter tool again). + +If the problem persists, please report it in the [issue tracker](https://code.google.com/p/support-tools/issues/list). Be sure to include the name of the Google Code project you are trying to export. + +## Error "Internal Server Error." ## + +Aw snap! Sometimes gremlins work their way into the system. We do our best to stamp them out, but with Google's free food it is hard to avoid snacking after midnight... + +If you see this error someone will be looking into it. Wait a while and retry your project export again. + +## Error "GitHub code import failure." ## + +This error occurs when the GitHub code import API fails. Usually this issue is transient. But if it persists, contact Google or GitHub. + +## Error "Project already exists." ## + +Projects will be migrated to GitHub creating a repo with the same name as the Google Code project. It is not possible to specify a different name for the GitHub repo. + +If your GitHub account already has a repo with the name of the project you wish to export, you will be prohibited from migrating that project from Google Code. + +To work around this, you can temporarily rename your GitHub repo by going to the repo's settings. \ No newline at end of file diff --git a/IssueExporterTool.md b/IssueExporterTool.md new file mode 100644 index 0000000..531492e --- /dev/null +++ b/IssueExporterTool.md @@ -0,0 +1,101 @@ +If you are migrating a project to Bitbucket or GitHub, the Issue Exporter tool can help you migrate your Google Code issue tracker items to your project’s new home. + +If you are interested in migrating your issues to [gitlab.com](http://gitlab.com), a [separate tool](https://gitlab.com/o9000/google-code-to-gitlab) has been developed. (Though not tested or supported by Google.) + +# Install Python # +First you need to [install Python](https://www.python.org/downloads/), though it should be already installed on most Mac and Linux machines. + +Next, [clone the support-tools Google Code project](https://code.google.com/p/support-tools/source/checkout) (i.e. _this_ project's source code). + +``` +git clone https://code.google.com/p/support-tools/ +``` + +# Use Google Takeout to Get Issue Data # +With the Python runtime installed, next we need to download a dump of all of your project's issues. To create an archive of all of your Google Code projects' issues, head to Google Takeout: +https://www.google.com/settings/takeout + +Google Takeout allows you to export project data from many Google Services, but for now we are only interested in "Google Code Project Hosting". + +Google Takeout will create an archive of all of your project’s issues. Note that this is only available for projects which you are an owner of. You will not be able to use Google Takeout to export archives of issues for other open-source projects. + +Depending on the number of Google Code projects you own, and the number of issues they have, exporting an archive may take a very long time. Google Takeout will notify you when your archive is ready. + +Once you have your issue archive, extract the file named `GoogleCodeProjectHosting.json`. This is a JSON dump of all of your projects' issues. (The issues for multiple Google Code projects will be stored in that single file.) + +We will then run a few scripts on this data dump to upload your issues to another location. There are instructions are different for exporting issues to GitHub or Bitbucket. + +# Exporting to GitHub # +Next we will run a script, `github_issue_convert.py`, to upload your project’s issues to a GitHub project. + +## Personal Access Token ## +The next step is to create a personal access token. This is a special password that you will use for this process. When the migration is complete, you can revoke this password. + +Create a personal access token by visting https://github.com/settings/applications and create a new "Personal Access Token". Be sure to check the "public\_repo" scope. (Which authorizes this access token to modify your public repos.) + +## Running the Script ## +You are now all set to migrate your issues to GitHub. + +The script has several parameters: +``` + usage: github_issue_converter.py + [-h] + --github_oauth_token GITHUB_OAUTH_TOKEN + --github_owner_username GITHUB_OWNER_USERNAME + --github_repo_name GITHUB_REPO_NAME + --issue_file_path ISSUE_FILE_PATH + --project_name PROJECT_NAME +``` + +The parameters are as follows: + + * `github_owner_username` is the name of the GitHub repo owner, i.e. you. (e.g. “chrsmith”) + * `github_oauth_token` this is the access token you generated above. + * `github_repo_name` is the name of the repository you will be importing the issues into. + * `issue_file_path` is the file path to your GoogleCodeProjectHosting.json file. + * `project_name` is the name of the Google Code project whose issues you are exporting. For example "support-tools". + +To run the conversion script, run the following: +``` +python \ + googlecode-issues-exporter/github_issue_converter.py \ + --github_oauth_token="$GH_ACCESS_TOKEN" \ + --github_owner_username= \ + --github_repo_name= \ + --issue_file_path= \ + --project_name= +``` + +### Speeding Things Up ### +Exporting issues and comments to GitHub will be _very, very_ slow. This is because the script is designed to send requests slow enough to not run afoul of GitHub's anti-abuse rate limiting. + +You can get the anti-abuse rate limited for your account by [contacting GitHub](https://github.com/contact?form%5Bsubject%5D=Google+Code+Export:+API+Abuse+Rate+Limits). If you get the rate limit raised for your account, add a `--rate_limit=false` flag to the GitHub issue converter. + +For more information please see the GitHub APIs [section on rate-limiting](https://developer.github.com/v3/#rate-limiting), and search for "Abuse Rate Limits". + +# Exporting to Bitbucket # +Exporting issue data to Bitbucket is slightly different. Rather than using an API to export issues individually, Bitbucket takes a single archive and will process all issues at once. + +We will run a script, `bitbucket_issue_convert.py`, to convert your Google Code issues dump into a format that can be imported into Bitbucket. + +The Bitbucket script is very similar to the GitHub import script above. + +``` +python googlecode-issues-exporter/bitbucket_issue_converter.py \ + --issue_file_path= \ + --project_name= \ + --default_owner_username= +``` + +This will generate the file named `db-1.0.json`, which contains your project’s issues and comments in a format that Bitbucket can ingest. + +Next you need to convert it to a zip file: + +``` +zip -r bitbucket-issues.zip db-1.0.json +``` + +## Upload the Bitbucket Issue Dump ## +Open up your project on Bitbucket, and on the "Settings" page head to "Import & Export" under "Issues". + +Select `bitbucket-issues.zip` file and click "Start import". Done! Now you should have all of your Google Code issues in Bitbucket. \ No newline at end of file diff --git a/IssueMirror.md b/IssueMirror.md new file mode 100644 index 0000000..e9f8dbb --- /dev/null +++ b/IssueMirror.md @@ -0,0 +1,23 @@ +# Issue Mirror # + +As part of the export process, either to GitHub or using the [Issue Exporter](IssueExporterTool.md) tool, issue attachments are presented as a link. This wiki describes how those links are generated. + +All _public_ Google Code issue attachments are mirrored to [Google Cloud Storage](https://cloud.google.com/storage/), in the bucket `google-code-attachments`. + +You can access a project's issue attachments by generating a URL based on the issue's information. The format is as follows: + +``` + "http://storage.googleapis.com/google-code-attachments" + + "/" + project_name + + "/issue-" + issue_number + + "/comment-" + comment_number + + "/" + file_name +``` + +The end result will be a URL to the project's issue, for example: + +http://storage.googleapis.com/google-code-attachments/issue-export-test/issue-4/comment-1/misc_file2.txt + +If an attachment is added to the initial issue report, then it is considered to be at `comment_number` 0. + +Note: There was a bug in an earlier version of the Issue Mirror, which caused comment numbers for issues mirrored to Google Cloud Storage to match Google Code. This only occurred if some of the comments on the issue were deleted, which occurred for < 5% of issue attachments. This issue has since been fixed. \ No newline at end of file diff --git a/LICENSE b/LICENSE deleted file mode 100644 index d645695..0000000 --- a/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/MigratingToBitbucket.md b/MigratingToBitbucket.md new file mode 100644 index 0000000..43202f1 --- /dev/null +++ b/MigratingToBitbucket.md @@ -0,0 +1,30 @@ +[Bitbucket](https://bitbucket.org) has been providing both public private source hosting to the internet since 2008. This document will cover how to migrate a project on Google Code to Bitbucket. However, Bitbucket only supports the Mercurial and Git protocols. SVN-based projects can be imported, but will be converted as part of the migration. + +# Sign in to Bitbucket # +If you do not already have a Bitbucket account, create one and log in. You do not need to create a new Bitbucket project before importing your Google Code project; when you start the importer tool, the Bitbucket project will be created for you. + +# Create a new Project via Import # +Once you have logged into Bitbucket, simply click Create to begin creating a new repository and then click the "importing a repository" link. + +That will lead you to a simple wizard for importing projects. Select "Google Code" from the Source combo box, and then enter your Google Code project name. You can find more information in the [Bitbucket Import documentation](https://confluence.atlassian.com/display/BITBUCKET/Import+code+from+an+existing+project). + +The Bitbucket importer may take a few minutes to import your project, depending on the size of your repo. + +Note that the "Issue tracking" and "Wiki" checkboxes are for whether or not you want your Bitbucket project to have the Issue tracking and Wiki _features_. Bitbucket will not import your Google Code issues or wikis. You will need to run separate tools to export that data from Google Code. + +# Project Issues # +To export project issues to Bitbucket, see the documentation for the [Issue Exporter](IssueExporterTool.md). + +# Project Wikis # +To export project wikis to Bitbucket, see the documentation for the [Wiki-to-Markdown Tool](WikiToMarkdownTool.md). + +# URL Redirection # +Once a project has been successfully exported to Bitbucket, you will want to update your project's homepage on Google Code to avoid confusion. + +Some project owners simply update their project homepage's text to indicate it has moved. For example [subtext](http://code.google.com/p/subtext) or [bwapi](http://code.google.com/p/bwapi). + +Another option is to set the Google Code "project moved" flag. When set, attempts to access the project will take users to an interstitial page indicating the new project location. In the future, the page will automatically redirect your new project on bitbucket.org. + +To set the "project moved" flag, navigate to your project's advanced admin page, at https://code.google.com/p/project-name/adminAdvanced. + +Once there, enter the new project home page URL under "project moved". For example: https://bitbucket.org/larryp/search_engine. Finally click the "Project Moved" button. \ No newline at end of file diff --git a/MigratingToGitHub.md b/MigratingToGitHub.md new file mode 100644 index 0000000..d9e7051 --- /dev/null +++ b/MigratingToGitHub.md @@ -0,0 +1,49 @@ +[GitHub](https://github.com) has been providing both public and private source hosting since 2008. This document will cover how to migrate a Google Code project to GitHub. + +Note that while Google Code will host source code using the SVN, Mercurial, or Git protocol, GitHub chiefly supports Git. Mercurial or SVN-based Google Code projects will be converted to the Git protocol as part of the migration. + +# Project Source # +There are several options for importing your source code into GitHub, depending on the type of source control system you use. The rest of this post will cover how to migrate git-based projects to GitHub. But if you are using another VCS, such as SVN or Mercurial, see this [GitHub article](https://help.github.com/articles/importing-your-project-to-github/). + +## Using Git ## +To migrate your project's source to GitHub using command-line tools, first use your GitHub account to create a new, empty repository. Next, add the new GitHub repo as a "remote" to your Google Code project. You can see the git remote originally pointing to Google Code by typing `git remote -v`. + +To move the source code to your new GitHub project, simply change the "origin" remote to point to GitHub. + +``` +$ git remote set-url origin \ + https://github.com/chrsmith/.git +$ git remote -v +origin https://github.com/chrsmith/.git (fetch) +origin https://github.com/chrsmith/.git (push) +``` + +Next, push your changes to the new remote: + +``` +git push -u origin --all # push the repo and its refs +git push -u origin --tags # push any tags +``` + +Once the data has been pushed, your project's source code and history should all be available on GitHub. + +If your git push fails for some reason, for example "error: git-remote-https died of signal 13" run `git fsck` to diagnose the problem. GitHub also provides documentation for [Importing a Git repository using the command line](https://help.github.com/articles/importing-a-git-repository-using-the-command-line/). + +With the project source migrated, the next step is to bring over Google Code project's issues and wikis. + +# Project Issues # +To export project issues to GitHub, see the documentation for the [Issue Exporter](IssueExporterTool.md). + +# Project Wikis # +To export project wikis to GitHub, see the documentation for the [Wiki-to-Markdown Tool](WikiToMarkdownTool.md). + +# URL Redirection # +Once a project has been successfully exported to GitHub, you will want to update your project's homepage on Google Code to avoid confusion. + +Some project owners simply update their project homepage's text to indicate it has moved. For example [subtext](http://code.google.com/p/subtext) or [bwapi](http://code.google.com/p/bwapi). + +Another option is to set the Google Code "project moved" flag. When set, attempts to access the project will take users to an interstitial page indicating the new project location. Future requests to the Google Code projects will automatically be redirected to the new location on github.com. + +To set the "project moved" flag, navigate to your project's advanced admin page, at https://code.google.com/p/project-name/adminAdvanced. + +Once there, enter the new project home page URL under "project moved". For example: https://github.org/larryp/search_engine. Finally click the "Project Moved" button. \ No newline at end of file diff --git a/MigratingToGitLab.md b/MigratingToGitLab.md new file mode 100644 index 0000000..d412e91 --- /dev/null +++ b/MigratingToGitLab.md @@ -0,0 +1,37 @@ +[GitLab](http://gitlab.com/) is a service that hosts git source code repositories, along with wikis and issue tracking. But unlike other services such as GitHub, you can also run GitLab on your own infrastructure. This document will cover how to migrate a project from Google Code to GitLab. + +# Sign in to GitLab # +You can sign-into GitLab using an !OpenID identity, such as your Google account. From you will see the import from Google Code option available on the "New Project" page. + +But first, we need to get the issue tracker data for your Google Code project. + +# Obtain your Google Code Issue data # + +Project migration to GitLab is keyed off of the Google Code Project Hosting archives returned from Google Takeout. To create an archive of all of your Google Code projects' issues, head to Google Takeout: https://www.google.com/settings/takeout + +Google Takeout allows you to export project data from many Google Services, but for now we are only interested in "Google Code Project Hosting". + +Google Takeout will create an archive of all of your project’s issues. Note that this is only available for projects which you are an owner of. You will not be able to use Google Takeout to export archives of issues for other open-source projects. (And consequently you cannot migrate those to GitLab.) + +Depending on the number of Google Code projects you own, and the number of issues they have, exporting an archive may take a very long time. Google Takeout will notify you when your archive is ready. + +Once you have your issue archive, extract the file named `GoogleCodeProjectHosting.json`. This is a JSON dump of all of your projects' issues. (The issues for multiple Google Code projects will be stored in that single file.) + +Upload the .json file to GitLab as part of the project migration. + +# Migrate your Project(s) # + +GitLab's New Project flow guides you through each step of the migration process. With the list of projects obtained from your JSON dump, simply click "Import" for any projects you want to have migrated to GitLab. + +As an optional step, GitLab provides is the ability to map Google Code email addresss to another name. For example, convert the obfuscated "johnsmi...@gmail.com" from the `GoogleCodeProjectHosting.json` dump to a GitLab user, or a full name such as "John Smith". + +# URL Redirection # +Once a project has been successfully exported to GitLab, you will want to update your project's homepage on Google Code to avoid confusion. + +Some project owners simply update their project homepage's text to indicate it has moved. For example [subtext](http://code.google.com/p/subtext) or [bwapi](http://code.google.com/p/bwapi). + +Another option is to set the Google Code "project moved" flag. When set, attempts to access the project will take users to an interstitial page indicating the new project location. In the future, the page will automatically redirect your new project on gitlab.com. + +To set the "project moved" flag, navigate to your project's advanced admin page, at https://code.google.com/p/project-name/adminAdvanced. + +Once there, enter the new project home page URL under "project moved". Finally click the "Project Moved" button. \ No newline at end of file diff --git a/MigratingToSourceForge.md b/MigratingToSourceForge.md new file mode 100644 index 0000000..a86e4be --- /dev/null +++ b/MigratingToSourceForge.md @@ -0,0 +1,27 @@ +[SourceForge](http://sourceforge.net/) has been hosting open-source software since 1999, and boasts over [400,000 projects](http://sourceforge.net/about). This document will cover how to migrate a project from Google Code to SourceForge, which supports the SVN, Git, and Mercurial version control systems. + +The migration will be done using SourceForge's [Google Code Project Importer](https://sourceforge.net/p/import_project/google-code/). + +# Sign in to SourceForge # +If you do not already have a SourceForge account, create one and log in. + +# Navigate to the Importer Tool # +Navigate to the easy-to-use Google Code Project Importer: +https://sourceforge.net/p/import_project/google-code/ + +This tool will import your project’s wikis, issues, existing downloads, and, of course, your project’s source code. You can learn more specifics by reading the tool’s [documentation](http://sourceforge.net/p/forge/documentation/Google%20Code%20Importer/). + +You do not need to create a new SourceForge project before importing your Google Code project; when you start the importer tool, the SourceForge project will be created for you. + +Once you click Import, the process will start. You will get emails as various import steps complete, such as when all the wiki pages have been migrated. + +# URL Redirection # +Once a project has been successfully exported to SourceForge, you will want to update your project's homepage on Google Code to avoid confusion. + +Some project owners simply update their project homepage's text to indicate it has moved. For example [subtext](http://code.google.com/p/subtext) or [bwapi](http://code.google.com/p/bwapi). + +Another option is to set the Google Code "project moved" flag. When set, attempts to access the project will take users to an interstitial page indicating the new project location. In the future, the page will automatically redirect your new project on sourceforce.net. + +To set the "project moved" flag, navigate to your project's advanced admin page, at https://code.google.com/p/project-name/adminAdvanced. + +Once there, enter the new project home page URL under "project moved". For example: https://sourceforge.net/p/fuego. Finally click the "Project Moved" button. \ No newline at end of file diff --git a/ProjectHome.md b/ProjectHome.md new file mode 100644 index 0000000..80b34bf --- /dev/null +++ b/ProjectHome.md @@ -0,0 +1,26 @@ +This project contains tools for exporting data from Google Code project hosting. + +# Google Code to GitHub Exporter # +The quickest way to export data from Google Code is to use the [Google Code-to-GitHub exporter](http://code.google.com/export-to-github/). This tool allows you to export any public Google Code repository to your GitHub account. + +For more information, please see the [Exporter FAQ](GitHubExporterFAQ.md). + +# Project Migration # +There are guides for migrating Google Code projects to other open-source hosting services: + + * [How to migrate a project to GitHub](MigratingToGitHub.md) + * [How to migrate a project to Bitbucket](MigratingToBitbucket.md) + * [How to migrate a project to SourceForge](MigratingToSourceForge.md) + * NEW [How to migrate a project to GitLab](MigratingToGitLab.md) + +# Issue Tracker # +The Google Code Issue Tracker has been integrated with Google Takeout. There is a stand-alone tool for exporting an archive of a Google Code project's issues and importing them into GitHub or Bitbucket. + +See [Issue Exporter](IssueExporterTool.md). + +For information specifically about issue attachments, see [Issue Mirror](IssueMirror.md). + +# Wiki Data # +Google Code's wiki format is non-standard. There is a stand-alone tool for converting Google Code's wiki format to GitHub-flavored Markdown. + +See [Wiki-to-Markdown tool](WikiToMarkdownTool.md). \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 19288cf..0000000 --- a/README.md +++ /dev/null @@ -1,4 +0,0 @@ -#Google Code Support Tools# - -This project contains tools related to exporting data from Google Code. - diff --git a/WikiToMarkdownTool.md b/WikiToMarkdownTool.md new file mode 100644 index 0000000..8c191d0 --- /dev/null +++ b/WikiToMarkdownTool.md @@ -0,0 +1,90 @@ +This document describes how you can convert Google Code wiki pages to [GitHub-flavored Markdown](https://help.github.com/articles/github-flavored-markdown/). This variant of Markdown is also compatible with Bitbucket’s wiki format. + +Once the Google Code project's .wiki files have been converted to Markdown, you will need to import them into your GitHub or Bitbucket repo using their web UI, or check the files directly into the repo. + +# Install Python # +First you need to [install Python](https://www.python.org/downloads/), though it should be already installed on most Mac and Linux machines. + +Next, [clone the support-tools Google Code project](https://code.google.com/p/support-tools/source/checkout) (i.e. _this_ project's source code). + +``` +git clone https://code.google.com/p/support-tools/ +``` + +# Run the Converter # +With the conversion tool, all you need to do is simply run it on your project’s wiki pages. + +Google Code stores wikis along with project source code, but the exact location depends on the type of project (Subversion, Mercurial, or Git). + +Git and Mercurial projects store wikis in a separate repo, so to get access to your wiki files you need to clone the "wiki" subrepo. For example, if you want to get access to all of the wiki files in the "codesearch" project, simply clone the "codesearch.wiki" repository. + +``` +hg clone https://code.google.com/p/codesearch.wiki/ +``` + +Subversion projects store the wikis directly in the svn repository, in the `/wiki` folder. + +## Running the converter ## + +To run the `wiki2gfm` tool, simply run: + +``` +python ./wiki2gfm.py \ + --input_file \ + --output_file +``` + +The conversion process may output warnings to the console. This is expected as Google Code’s wiki syntax cannot always be converted to Markdown. Take a look over these warnings, along with the output to ensure no undesirable formatting has occurred. + +There are several additional flags that may be of use: + +`--project`: The name of your Google Code project. It is possible to refer to your project name indirectly in wiki syntax; providing this option makes it possible for the converter to resolve your project name when this occurs. + +`--wikipages_list`: The list of wiki pages that are assumed to exist for the purpose of auto-linking to other pages. Wiki syntax allows auto-linking to other wiki pages, if they exist. Providing a list of wiki pages that do actually exist to the converter allows it to optimistically link to the converted page of another wiki. + +`--wikipages_path`: An alternate way of providing the same information as --wikipages\_list, this is a list of directories to search for .wiki files, the names of which are used as if they were provided via --wikipages\_list. + +`--[no_]symmetric_headers`: Controls whether or not headers in Markdown are given symmetric header guards. In Markdown, a header is indicated by a number of # symbols, and only the leading group of symbols is required; however, for aesthetic purposes it is sometimes desirable for the header to be surrounded by equal numbers of #. This flag controls this. + +# Bulk conversion # +For projects with many wiki pages, manually typing in the name of each wiki file can get tedious. To bulk-convert all of a project’s wiki pages, you can use the following Bash script: + +``` +#!/bin/bash + +# Bulk converts wiki pages. Usage: +# bulk-convert.sh +USAGE="Bulk converter for wiki pages. + +Example usage: +$ mkdir converted-wikis +$ ./bulk-convert.sh \ + ./support-tools/wiki_to_md/wiki2gfm.py \ + ./google-code-project.wiki/ \ + ./converted-wikis/ +" + +if [ $# -eq 0 ] ; then + echo "$USAGE" + echo + exit 1 +fi + +PATH_TO_WIKI2GMF=$1 +PATH_TO_WIKIS=$2 +OUTPUT_DIR=$3 + +for file in `ls $PATH_TO_WIKIS` +do + printf "**************************\n" + printf "Converting $file\n" + printf "**************************\n" + + python $PATH_TO_WIKI2GMF \ + --input_file=$PATH_TO_WIKIS/$file \ + --output_file=$OUTPUT_DIR/$file.md + + printf "done\n\n" + +done +``` \ No newline at end of file diff --git a/googlecode-issues-exporter/__init__.py b/googlecode-issues-exporter/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/googlecode-issues-exporter/bitbucket_issue_converter.py b/googlecode-issues-exporter/bitbucket_issue_converter.py deleted file mode 100644 index 65ede2b..0000000 --- a/googlecode-issues-exporter/bitbucket_issue_converter.py +++ /dev/null @@ -1,234 +0,0 @@ -# Copyright 2014 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tool for converting Google Code issues to a format accepted by BitBucket. - -Most BitBucket concepts map cleanly to their Google Code equivalent, with the -exception of the following: - - Issue Assignee is called an Owner - - Issue Reporter is called an Author - - Comment User is called an Author -""" - -import argparse -import json -import sys - -import issues - - -def _getKind(kind): - mapping = { - "defect": "bug", - "enhancement": "enhancement", - "task": "task", - "review": "proposal", - "other": "bug", - } - return mapping.get(kind.lower(), "bug") - - -def _getPriority(priority): - mapping = { - "low": "trivial", - "medium": "minor", - "high": "major", - "critical": "critical", - } - return mapping.get(priority.lower(), "minor") - - -def _getStatus(status): - mapping = { - "new": "new", - "fixed": "resolved", - "invalid": "invalid", - "duplicate": "duplicate", - "wontfix": "wontfix", - } - return mapping.get(status.lower(), "new") - - -def _getTitle(title): - if len(title) < 255: - return title - return title[:250] + "[...]" - - -class UserService(issues.UserService): - """BitBucket user operations. - """ - - def IsUser(self, username): - """Returns wheter a username is a valid user. - - BitBucket does not have a user api, so accept all usernames. - """ - return True - - -class IssueService(issues.IssueService): - """Abstract issue operations. - - Handles creating and updating issues and comments on an user API. - """ - def __init__(self): - self._bitbucket_issues = [] - self._bitbucket_comments = [] - - def GetIssues(self, state="open"): - """Gets all of the issue for the repository. - - Since BitBucket does not have an issue API, always returns an empty list. - - Args: - state: The state of the repository can be either 'open' or 'closed'. - - Returns: - An empty list. - """ - return [] - - def CreateIssue(self, googlecode_issue): - """Creates an issue. - - Args: - googlecode_issue: An instance of GoogleCodeIssue - - Returns: - The issue number of the new issue. - - Raises: - ServiceError: An error occurred creating the issue. - """ - bitbucket_issue = { - "assignee": googlecode_issue.GetOwner(), - "content": googlecode_issue.GetDescription(), - "content_updated_on": googlecode_issue.GetContentUpdatedOn(), - "created_on": googlecode_issue.GetCreatedOn(), - "id": googlecode_issue.GetId(), - "kind": _getKind(googlecode_issue.GetKind()), - "priority": _getPriority(googlecode_issue.GetPriority()), - "reporter": googlecode_issue.GetAuthor(), - "status": _getStatus(googlecode_issue.GetStatus()), - "title": _getTitle(googlecode_issue.GetTitle()), - "updated_on": googlecode_issue.GetUpdatedOn() - } - self._bitbucket_issues.append(bitbucket_issue) - return googlecode_issue.GetId() - - def CloseIssue(self, issue_number): - """Closes an issue. - - Args: - issue_number: The issue number. - """ - - def CreateComment(self, issue_number, source_issue_id, - googlecode_comment, project_name): - """Creates a comment on an issue. - - Args: - issue_number: The issue number. - source_issue_id: The Google Code issue id. - googlecode_comment: An instance of GoogleCodeComment - project_name: The Google Code project name. - """ - bitbucket_comment = { - "content": googlecode_comment.GetDescription(), - "created_on": googlecode_comment.GetCreatedOn(), - "id": googlecode_comment.GetId(), - "issue": googlecode_comment.GetIssue().GetId(), - "updated_on": googlecode_comment.GetUpdatedOn(), - "user": googlecode_comment.GetAuthor() - } - self._bitbucket_comments.append(bitbucket_comment) - - def WriteIssueData(self, default_issue_kind): - """Writes out the json issue and comments data to db-1.0.json. - """ - issues_data = { - "issues": self._bitbucket_issues, - "comments": self._bitbucket_comments, - "meta": { - "default_kind": default_issue_kind - } - } - with open("db-1.0.json", "w") as issues_file: - issues_json = json.dumps(issues_data, sort_keys=True, indent=4, - separators=(",", ": ")) - issues_file.write(issues_json) - - -def ExportIssues(issue_file_path, project_name, - user_file_path, default_issue_kind): - """Exports all issues for a given project. - """ - issue_service = IssueService() - user_service = UserService() - - issue_data = issues.LoadIssueData(issue_file_path, project_name) - user_map = issues.LoadUserData(user_file_path, user_service) - - issue_exporter = issues.IssueExporter( - issue_service, user_service, issue_data, project_name, user_map) - - try: - issue_exporter.Init() - issue_exporter.Start() - issue_service.WriteIssueData(default_issue_kind) - print "\nDone!\n" - except IOError, e: - print "[IOError] ERROR: %s" % e - except issues.InvalidUserError, e: - print "[InvalidUserError] ERROR: %s" % e - - -def main(args): - """The main function. - - Args: - args: The command line arguments. - - Raises: - ProjectNotFoundError: The user passed in an invalid project name. - """ - parser = argparse.ArgumentParser() - parser.add_argument("--issue_file_path", required=True, - help="The path to the file containing the issues from" - "Google Code.") - parser.add_argument("--project_name", required=True, - help="The name of the Google Code project you wish to" - "export") - parser.add_argument("--user_file_path", required=False, - help="The path to the file containing a mapping from" - "email address to bitbucket username") - parser.add_argument("--default_issue_kind", required=False, - help="A non-null string containing one of the following" - "values: bug, enhancement, proposal, task. Defaults to" - "bug") - parsed_args, _ = parser.parse_known_args(args) - - # Default value. - if not parsed_args.default_issue_kind: - print "Using default issue kind of 'bug'." - parsed_args.default_issue_kind = "bug" - - ExportIssues( - parsed_args.issue_file_path, parsed_args.project_name, - parsed_args.user_file_path, parsed_args.default_issue_kind) - - -if __name__ == "__main__": - main(sys.argv) diff --git a/googlecode-issues-exporter/bitbucket_issue_converter_test.py b/googlecode-issues-exporter/bitbucket_issue_converter_test.py deleted file mode 100644 index 7b6b008..0000000 --- a/googlecode-issues-exporter/bitbucket_issue_converter_test.py +++ /dev/null @@ -1,195 +0,0 @@ -# Copyright 2013 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for the BitBucket Services.""" - -# pylint: disable=missing-docstring,protected-access - -import unittest - -import bitbucket_issue_converter -import issues - -from issues_test import DEFAULT_USERNAME -from issues_test import SINGLE_COMMENT -from issues_test import SINGLE_ISSUE -from issues_test import COMMENT_ONE -from issues_test import COMMENT_TWO -from issues_test import COMMENT_THREE -from issues_test import COMMENTS_DATA -from issues_test import NO_ISSUE_DATA -from issues_test import USER_MAP - - -# The BitBucket username. -BITBUCKET_USERNAME = DEFAULT_USERNAME -# The BitBucket repo name. -BITBUCKET_REPO = "repo" - - -class TestUserService(unittest.TestCase): - """Tests for the UserService.""" - - def setUp(self): - self._bitbucket_user_service = bitbucket_issue_converter.UserService() - - def testIsUser123(self): - is_user = self._bitbucket_user_service.IsUser("username123") - self.assertTrue(is_user) - - def testIsUser321(self): - is_user = self._bitbucket_user_service.IsUser("username321") - self.assertTrue(is_user) - - -class TestIssueService(unittest.TestCase): - """Tests for the IssueService.""" - - def setUp(self): - self._bitbucket_issue_service = bitbucket_issue_converter.IssueService() - self.maxDiff = None - - def testCreateIssue(self): - issue_body = { - "assignee": "default_username", - "content": ( - "```\none\n```\n\nOriginal issue reported on code.google.com" - " by `a_uthor` on last year\n" - "- **Labels added**: added-label\n" - "- **Labels removed**: removed-label\n"), - "content_updated_on": "last month", - "created_on": "last year", - "id": 1, - "kind": "bug", - "priority": "minor", - "reporter": None, - "status": "resolved", - "title": "issue_title", - "updated_on": "last year", - } - issue_number = self._bitbucket_issue_service.CreateIssue(SINGLE_ISSUE) - self.assertEqual(1, issue_number) - actual = self._bitbucket_issue_service._bitbucket_issues[0] - self.assertEqual(issue_body, actual) - - def testCloseIssue(self): - # no-op - self._bitbucket_issue_service.CloseIssue(123) - - # TODO(chris): Add testcase for an issue comment with attachments. - def testCreateComment(self): - comment_body = { - "content": ( - "```\none\n```\n\nOriginal issue reported on code.google.com " - "by `a_uthor` on last year\n" - "- **Labels added**: added-label\n" - "- **Labels removed**: removed-label\n"), - "created_on": "last year", - "id": 1, - "issue": 1, - "updated_on": "last year", - "user": "a_uthor", - } - self._bitbucket_issue_service.CreateComment( - 1, "1", SINGLE_COMMENT, BITBUCKET_REPO) - actual = self._bitbucket_issue_service._bitbucket_comments[0] - self.assertEqual(comment_body, actual) - - -class TestIssueExporter(unittest.TestCase): - """Tests for the IssueService.""" - - def setUp(self): - self._bitbucket_user_service = bitbucket_issue_converter.UserService() - self._bitbucket_issue_service = bitbucket_issue_converter.IssueService() - self.issue_exporter = issues.IssueExporter( - self._bitbucket_issue_service, self._bitbucket_user_service, - NO_ISSUE_DATA, BITBUCKET_REPO, USER_MAP) - self.issue_exporter.Init() - - def testGetAllPreviousIssues(self): - self.assertEqual(0, len(self.issue_exporter._previously_created_issues)) - self.issue_exporter._GetAllPreviousIssues() - self.assertEqual(0, len(self.issue_exporter._previously_created_issues)) - - def testCreateIssue(self): - issue_number = self.issue_exporter._CreateIssue(SINGLE_ISSUE) - self.assertEqual(1, issue_number) - - def testCreateComments(self): - self.assertEqual(0, self.issue_exporter._comment_number) - self.issue_exporter._CreateComments(COMMENTS_DATA, 1234, SINGLE_ISSUE) - self.assertEqual(4, self.issue_exporter._comment_number) - - def testStart(self): - self.issue_exporter._issue_json_data = [ - { - "id": "1", - "title": "Title1", - "state": "open", - "status": "New", - "comments": { - "items": [COMMENT_ONE, COMMENT_TWO, COMMENT_THREE], - }, - "labels": ["Type-Issue", "Priority-High"], - "owner": {"kind": "projecthosting#issuePerson", - "name": "User1" - }, - "published": "last year", - "updated": "last month", - }, - { - "id": "2", - "title": "Title2", - "state": "closed", - "status": "Fixed", - "owner": {"kind": "projecthosting#issuePerson", - "name": "User2" - }, - "labels": [], - "comments": { - "items": [COMMENT_ONE], - }, - "published": "last month", - "updated": "last week", - }, - { - "id": "3", - "title": "Title3", - "state": "closed", - "status": "WontFix", - "comments": { - "items": [COMMENT_ONE, COMMENT_TWO], - }, - "labels": ["Type-Defect"], - "owner": {"kind": "projecthosting#issuePerson", - "name": "User3" - }, - "published": "last week", - "updated": "yesterday", - }] - - self.issue_exporter.Start() - - self.assertEqual(3, self.issue_exporter._issue_total) - self.assertEqual(3, self.issue_exporter._issue_number) - # Comment counts are per issue and should match the numbers from the last - # issue created, minus one for the first comment, which is really - # the issue description. - self.assertEqual(1, self.issue_exporter._comment_number) - self.assertEqual(1, self.issue_exporter._comment_total) - - -if __name__ == "__main__": - unittest.main(buffer=True) diff --git a/googlecode-issues-exporter/generate_user_map.py b/googlecode-issues-exporter/generate_user_map.py deleted file mode 100644 index fb49836..0000000 --- a/googlecode-issues-exporter/generate_user_map.py +++ /dev/null @@ -1,119 +0,0 @@ -# Copyright 2014 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tool for generating a user mapping from Google Code user to BitBucket user. -""" - -import argparse -import json -import sys - -import issues - - -class OptionalMap(dict): - """Dictionary that returns the key for missing items. """ - - def __missing__(self, key): - """Implements the dict interface. """ - return key - - -def addIfNotPresent(users, user): - """Adds a user if it is not already set.""" - if user not in users: - users[user] = user - - -def _CreateUsersDict(issue_data, project_name): - """Extract users from list of issues into a dict. - - Args: - issue_data: Issue data - project_name: The name of the project being exported. - - Returns: - Dict of users associated with a list of issues - """ - users = {} - for issue in issue_data: - googlecode_issue = issues.GoogleCodeIssue( - issue, project_name, OptionalMap()) - - reporting_user = googlecode_issue.GetAuthor() - addIfNotPresent(users, reporting_user) - - assignee_user = googlecode_issue.GetOwner() - addIfNotPresent(users, assignee_user) - - googlecode_comments = googlecode_issue.GetComments() - for comment in googlecode_comments: - googlecode_comment = issues.GoogleCodeComment(googlecode_issue, comment) - commenting_user = googlecode_comment.GetAuthor() - addIfNotPresent(users, commenting_user) - - return { - "users": users - } - - -def Generate(issue_file_path, project_name): - """Generates a user map for the specified issues. """ - issue_data = None - - user_file = open(issue_file_path) - user_data = json.load(user_file) - user_projects = user_data["projects"] - - for project in user_projects: - if project_name in project["name"]: - issue_data = project["issues"]["items"] - break - - if issue_data is None: - raise issues.ProjectNotFoundError( - "Project %s not found" % project_name) - - users = _CreateUsersDict(issue_data, project_name) - - with open("users.json", "w") as users_file: - user_json = json.dumps(users, sort_keys=True, indent=4, - separators=(",", ": "), ensure_ascii=False) - users_file.write(unicode(user_json)) - print "\nCreated file users.json.\n" - - -def main(args): - """The main function. - - Args: - args: The command line arguments. - - Raises: - issues.ProjectNotFoundError: The user passed in an invalid project name. - """ - parser = argparse.ArgumentParser() - parser.add_argument("--issue_file_path", required=True, - help="The path to the file containing the issues from" - "Google Code.") - parser.add_argument("--project_name", required=True, - help="The name of the Google Code project you wish to" - "export") - parsed_args, _ = parser.parse_known_args(args) - - Generate(parsed_args.issue_file_path, parsed_args.project_name) - - -if __name__ == "__main__": - main(sys.argv) diff --git a/googlecode-issues-exporter/github_issue_converter.py b/googlecode-issues-exporter/github_issue_converter.py deleted file mode 100644 index 6672b86..0000000 --- a/googlecode-issues-exporter/github_issue_converter.py +++ /dev/null @@ -1,479 +0,0 @@ -# Copyright 2013 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tool for uploading Google Code issues to GitHub. - - Issue migration from Google Code to GitHub. - This tools allows you to easily move your downloaded Google Code issues to - GitHub. - - To use this tool: - 1. Follow the instructions at https://code.google.com/p/support-tools/ to - download your issues from Google. - 2. Go to https://github.com/settings/applications and create a new "Personal - Access Token". - 3. Get the GitHub username of the owner of the repository and the repositories - name you wish to add the issues to. For example username: TheDoctor and - repository: SonicScrewdriver - 4. (Optional) If this option is skipped all issues will be assigned to the - owner of the repo. Make a file that contains a mapping from the Google - Code email address to the GitHub username for each user you wish to assign - issues too. The file should be newline seperated with one user per line. - The email address and username should be colon (':') seperated. For example - a file may look like this: - : - myemail@gmail.com:coolperson - otheruser@gmail.com:userother - 5. Then run the command: - python ./issue_migration.py \ - --github_oauth_token= \ - --github_owner_username= \ - --github_repo_name= \ - --issue_file_path= \ - --user_file_path="" -""" - -import argparse -import json -import sys -import time -import urllib - -import httplib2 -import issues - - -# The URL used for calls to GitHub. -GITHUB_API_URL = "https://api.github.com" -# The maximum number of retries to make for an HTTP request that has failed. -MAX_HTTP_REQUESTS = 3 -# The time (in seconds) to wait before trying to see if more requests are -# available. -REQUEST_CHECK_TIME = 60 * 5 -# A real kludge. GitHub orders the comments based on time alone, and because -# we upload ours relatively quickly we need at least a second in between -# comments to keep them in chronological order. -COMMENT_DELAY = 2 - - - -def _CheckSuccessful(response): - """Checks if the request was successful. - - Args: - response: An HTTP response that contains a mapping from 'status' to an - HTTP response code integer. - - Returns: - True if the request was succesful. - """ - return "status" in response and 200 <= int(response["status"]) < 300 - - -class GitHubService(object): - """A connection to GitHub. - - Handles basic HTTP operations to the GitHub API. - - Attributes: - github_owner_username: The username of the owner of the repository. - github_repo_name: The GitHub repository name. - rate_limit: Whether or not to rate limit API calls. - """ - - def __init__(self, github_owner_username, github_repo_name, - github_oauth_token, rate_limit, http_instance=None): - """Initialize the GitHubService. - - Args: - github_owner_username: The username of the owner of the repository. - github_repo_name: The GitHub repository name. - github_oauth_token: The oauth token to use for the requests. - http_instance: The HTTP instance to use, if not set a default will be - used. - """ - self.github_owner_username = github_owner_username - self.github_repo_name = github_repo_name - self._github_oauth_token = github_oauth_token - self._rate_limit = rate_limit - self._http = http_instance if http_instance else httplib2.Http() - - def _PerformHttpRequest(self, method, url, body="{}", params=None): - """Attemps to make an HTTP request for given method, url, body and params. - - If the request fails try again 'MAX_HTTP_REQUESTS' number of times. If the - request fails due to the the request limit being hit, wait until more - requests can be made. - - Args: - method: The HTTP request method as a string ('GET', 'POST', etc.). - url: The URL to make the call to. - body: The body of the request. - params: A dictionary of parameters to be used in the http call. - - Returns: - A tuple of an HTTP response (https://developer.github.com/v3/#schema) and - its content from the server which is decoded JSON. - """ - headers = { "User-Agent": "GoogleCodeIssueExporter/1.0" } - query = params.copy() if params else {} - query["access_token"] = self._github_oauth_token - request_url = "%s%s?%s" % (GITHUB_API_URL, url, urllib.urlencode(query)) - requests = 0 - while requests < MAX_HTTP_REQUESTS: - requests += 1 - response, content = self._http.request(request_url, method, - headers=headers, body=body) - if _CheckSuccessful(response): - return response, json.loads(content) - elif self._RequestLimitReached(): - requests -= 1 - self._WaitForApiThrottlingToEnd() - return response, json.loads(content) - - def PerformGetRequest(self, url, params=None): - """Makes a GET request. - - Args: - url: The URL to make the call to. - params: A dictionary of parameters to be used in the http call. - - Returns: - A tuple of an HTTP response (https://developer.github.com/v3/#schema) and - its content from the server which is decoded JSON. - """ - return self._PerformHttpRequest("GET", url, params=params) - - def PerformPostRequest(self, url, body): - """Makes a POST request. - - Args: - url: The URL to make the call to. - body: The body of the request. - - Returns: - A tuple of an HTTP response (https://developer.github.com/v3/#schema) and - its content from the server which is decoded JSON. - """ - if self._rate_limit and self._rate_limit in ["True", "true"]: - # Add a delay to all outgoing request to GitHub, as to not trigger their - # anti-abuse mechanism. This is separate from your typical rate limit, and - # only applies to certain API calls (like creating issues). And, alas, the - # exact quota is undocumented. So the value below is simply a guess. See: - # https://developer.github.com/v3/#abuse-rate-limits - req_min = 15 - time.sleep(60 / req_min) - return self._PerformHttpRequest("POST", url, body) - - def PerformPatchRequest(self, url, body): - """Makes a PATCH request. - - Args: - url: The URL to make the call to. - body: The body of the request. - - Returns: - A tuple of an HTTP response (https://developer.github.com/v3/#schema) and - its content from the server which is decoded JSON. - """ - return self._PerformHttpRequest("PATCH", url, body) - - def _GetRemainingRequests(self): - """Gets the number of remaining requests the user has this hour. - - Makes GET request to GitHub to get the number of remaining requests before - the hourly request limit is reached. - - Returns: - The number of remaining requests. - """ - url = ("%s/rate_limit?access_token=%s" % - (GITHUB_API_URL, self._github_oauth_token)) - _, content = self._http.request(url, "GET") - content = json.loads(content) - if "rate" in content and "remaining" in content["rate"]: - return int(content["rate"]["remaining"]) - return 0 - - def _RequestLimitReached(self): - """Returns true if the request limit has been reached.""" - return self._GetRemainingRequests() == 0 - - def _WaitForApiThrottlingToEnd(self): - """Waits until the user is allowed to make more requests.""" - sys.stdout.write("Hourly request limit reached. Waiting for new limit, " - "checking every %d minutes" % (REQUEST_CHECK_TIME/60)) - while True: - sys.stdout.write(".") - sys.stdout.flush() - time.sleep(REQUEST_CHECK_TIME) - if not self._RequestLimitReached(): - return - - -class UserService(issues.UserService): - """GitHub user operations. - - Handles user operations on the GitHub API. - """ - - GITHUB_USERS_URL = "/users" - - def __init__(self, github_service): - """Initialize the UserService. - - Args: - github_service: The GitHub service. - """ - self._github_service = github_service - - def _GetUser(self, username): - """Gets a GitHub user. - - Args: - username: The GitHub username to get. - - Returns: - A tuple of an HTTP response (https://developer.github.com/v3/#schema) and - its content from the server which is decoded JSON. - """ - user_url = "%s/%s" % (self.GITHUB_USERS_URL, username) - return self._github_service.PerformGetRequest(user_url) - - def IsUser(self, username): - """Checks if the GitHub user exists. - - Args: - username: The GitHub username to check. - - Returns: - True if the username exists. - """ - response, _ = self._GetUser(username) - return _CheckSuccessful(response) - - -class IssueService(issues.IssueService): - """GitHub issue operations. - - Handles creating and updating issues and comments on the GitHub API. - """ - - def __init__(self, github_service, comment_delay=COMMENT_DELAY): - """Initialize the IssueService. - - Args: - github_service: The GitHub service. - """ - self._github_service = github_service - self._comment_delay = comment_delay - # If the repo is of the form "login/reponame" then don't inject the - # username as it (or the organization) is already embedded. - if '/' in self._github_service.github_repo_name: - self._github_issues_url = "/repos/%s/issues" % \ - self._github_service.github_repo_name - else: - self._github_issues_url = ("/repos/%s/%s/issues" % - (self._github_service.github_owner_username, - self._github_service.github_repo_name)) - - def GetIssues(self, state="open"): - """Gets all of the issue for the GitHub repository. - - Args: - state: The state of the repository can be either 'open' or 'closed'. - - Returns: - The list of all of the issues for the given repository. - - Raises: - IOError: An error occurred accessing previously created issues. - """ - github_issues = [] - params = {"state": state, "per_page": 100, "page": 0} - while True: - params["page"] += 1 - response, content = self._github_service.PerformGetRequest( - self._github_issues_url, params=params) - if not _CheckSuccessful(response): - raise IOError("Failed to retrieve previous issues.\n\n%s" % content) - if not content: - return github_issues - else: - github_issues += content - return github_issues - - def CreateIssue(self, googlecode_issue): - """Creates a GitHub issue. - - Args: - googlecode_issue: An instance of GoogleCodeIssue - - Returns: - The issue number of the new issue. - - Raises: - issues.ServiceError: An error occurred creating the issue. - """ - issue_title = googlecode_issue.GetTitle() - # It is not possible to create a Google Code issue without a title, but you - # can edit an issue to remove its title afterwards. - if issue_title.isspace(): - issue_title = "" - issue = { - "title": issue_title, - "body": googlecode_issue.GetDescription(), - "assignee": googlecode_issue.GetOwner(), - "labels": googlecode_issue.GetLabels(), - } - response, content = self._github_service.PerformPostRequest( - self._github_issues_url, json.dumps(issue)) - - if not _CheckSuccessful(response): - # Newline character at the beginning of the line to allows for in-place - # updating of the counts of the issues and comments. - raise issues.ServiceError( - "\nFailed to create issue #%d '%s'.\n\n\n" - "Response:\n%s\n\n\nContent:\n%s" % ( - googlecode_issue.GetId(), issue_title, response, content)) - - return self._GetIssueNumber(content) - - def CloseIssue(self, issue_number): - """Closes a GitHub issue. - - Args: - issue_number: The issue number. - - Raises: - issues.ServiceError: An error occurred closing the issue. - """ - issue_url = "%s/%d" % (self._github_issues_url, issue_number) - json_state = json.dumps({"state": "closed"}) - response, content = self._github_service.PerformPatchRequest( - issue_url, json_state) - if not _CheckSuccessful(response): - raise issues.ServiceError("\nFailed to close issue #%s.\n%s" % ( - issue_number, content)) - - def CreateComment(self, issue_number, source_issue_id, - googlecode_comment, project_name): - """Creates a comment on a GitHub issue. - - Args: - issue_number: The issue number. - source_issue_id: The Google Code issue id. - googlecode_comment: A GoogleCodeComment instance. - project_name: The Google Code project name. - - Raises: - issues.ServiceError: An error occurred creating the comment. - """ - comment_url = "%s/%d/comments" % (self._github_issues_url, issue_number) - comment = googlecode_comment.GetDescription() - - json_body = json.dumps({"body": comment}) - response, content = self._github_service.PerformPostRequest( - comment_url, json_body) - - if not _CheckSuccessful(response): - raise issues.ServiceError( - "\nFailed to create issue comment for issue #%d\n\n" - "Response:\n%s\n\nContent:\n%s\n\n" % - (issue_number, response, content)) - time.sleep(self._comment_delay) - - def _GetIssueNumber(self, content): - """Get the issue number from a newly created GitHub issue. - - Args: - content: The content from an HTTP response. - - Returns: - The GitHub issue number. - """ - assert "number" in content, "Getting issue number from: %s" % content - return content["number"] - - -def ExportIssues(github_owner_username, github_repo_name, github_oauth_token, - issue_file_path, project_name, user_file_path, rate_limit): - """Exports all issues for a given project. - """ - github_service = GitHubService( - github_owner_username, github_repo_name, github_oauth_token, - rate_limit) - issue_service = IssueService(github_service) - user_service = UserService(github_service) - - issue_data = issues.LoadIssueData(issue_file_path, project_name) - user_map = issues.LoadUserData(user_file_path, user_service) - - # Add a special "user_requesting_export" user, which comes in handy. - user_map["user_requesting_export"] = github_owner_username - - issue_exporter = issues.IssueExporter( - issue_service, user_service, issue_data, project_name, user_map) - - try: - issue_exporter.Init() - issue_exporter.Start() - print "\nDone!\n" - except IOError, e: - print "[IOError] ERROR: %s" % e - except issues.InvalidUserError, e: - print "[InvalidUserError] ERROR: %s" % e - - -def main(args): - """The main function. - - Args: - args: The command line arguments. - - Raises: - ProjectNotFoundError: The user passed in an invalid project name. - """ - parser = argparse.ArgumentParser() - parser.add_argument("--github_oauth_token", required=True, - help="You can generate an oauth token here: " - "https://github.com/settings/applications") - parser.add_argument("--github_owner_username", required=True, - help="The project ownsers GitHub username") - parser.add_argument("--github_repo_name", required=True, - help="The GitHub repository you wish to add the issues" - "to.") - parser.add_argument("--issue_file_path", required=True, - help="The path to the file containing the issues from" - "Google Code.") - parser.add_argument("--project_name", required=True, - help="The name of the Google Code project you wish to" - "export") - parser.add_argument("--user_file_path", required=False, - help="The path to the file containing a mapping from" - "email address to github username.") - parser.add_argument("--rate_limit", required=False, default="True", - help="Rate limit GitHub requests to not run into" - "anti-abuse limits.") - parsed_args, _ = parser.parse_known_args(args) - - ExportIssues( - parsed_args.github_owner_username, parsed_args.github_repo_name, - parsed_args.github_oauth_token, parsed_args.issue_file_path, - parsed_args.project_name, parsed_args.user_file_path, - parsed_args.rate_limit) - - -if __name__ == "__main__": - main(sys.argv) diff --git a/googlecode-issues-exporter/github_issue_converter_test.py b/googlecode-issues-exporter/github_issue_converter_test.py deleted file mode 100644 index 5d6e667..0000000 --- a/googlecode-issues-exporter/github_issue_converter_test.py +++ /dev/null @@ -1,557 +0,0 @@ -# Copyright 2013 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for the GitHub Services.""" - -# pylint: disable=missing-docstring,protected-access - -import collections -import httplib -import json -import unittest -import urlparse - -import github_issue_converter -import issues - -from issues_test import DEFAULT_USERNAME -from issues_test import SINGLE_COMMENT -from issues_test import SINGLE_ISSUE -from issues_test import COMMENT_ONE -from issues_test import COMMENT_TWO -from issues_test import COMMENT_THREE -from issues_test import COMMENTS_DATA -from issues_test import NO_ISSUE_DATA -from issues_test import USER_MAP -from issues_test import REPO - - -# The GitHub username. -GITHUB_USERNAME = DEFAULT_USERNAME -# The GitHub repo name. -GITHUB_REPO = REPO -# The GitHub oauth token. -GITHUB_TOKEN = "oauth_token" -# The URL used for calls to GitHub. -GITHUB_API_URL = "https://api.github.com" - - -class FakeGitHubService(github_issue_converter.GitHubService): - """A fake of the GitHubService. - - This also allows for queueing of responses and there content into a reponse - queue. For example if you wanted a successful response and then a failure you - would call AddSuccessfulResponse and then AddFailureResponse. Then when a call - to _PerformHttpRequest is made the succesful response is made. The next call - would then return the failed response. - - If no responses are in the queue a succesful request with no content is - returned. - - Attributes: - github_owner_username: The username of the owner of the repository. - github_repo_name: The GitHub repository name. - github_oauth_token: The oauth token to use for the requests. - """ - - # pylint: disable=super-init-not-called - def __init__(self, github_owner_username, github_repo_name, - github_oauth_token): - """Initialize the FakeGitHubService. - - Args: - github_owner_username: The username of the owner of the repository. - github_repo_name: The GitHub repository name. - github_oauth_token: The oauth token to use for the requests. - - """ - self.github_owner_username = github_owner_username - self.github_repo_name = github_repo_name - self._github_oauth_token = github_oauth_token - self._action_queue = collections.deque([]) - - def AddSuccessfulResponse(self, content=None): - """Adds a succesfull response with no content to the reponse queue.""" - self.AddResponse(content=content) - - def AddFailureResponse(self): - """Adds a failed response with no content to the reponse queue.""" - self.AddResponse(httplib.BAD_REQUEST) - - def AddResponse(self, response=httplib.OK, content=None): - status = {"status": response} - full_response = {} - full_response["status"] = status - full_response["content"] = content if content else {} - self._action_queue.append(full_response) - - def _PerformHttpRequest(self, method, url, body="{}", params=None): - if not self._action_queue: - return {"status": httplib.OK}, {} - - full_response = self._action_queue.popleft() - return (full_response["status"], full_response["content"]) - - def PerformGetRequest(self, url, params=None): - """Makes a fake GET request. - - Args: - url: The URL to make the call to. - params: A dictionary of parameters to be used in the http call. - - Returns: - A tuple of a fake response and fake content. - """ - return self._PerformHttpRequest("GET", url, params=params) - - def PerformPostRequest(self, url, body): - """Makes a POST request. - - Args: - url: The URL to make the call to. - body: The body of the request. - - Returns: - A tuple of a fake response and content - """ - return self._PerformHttpRequest("POST", url, body=body) - - def PerformPatchRequest(self, url, body): - """Makes a PATCH request. - - Args: - url: The URL to make the call to. - body: The body of the request. - - Returns: - A tuple of a fake response and content - """ - return self._PerformHttpRequest("PATCH", url, body=body) - - -class Http2Mock(object): - """Mock httplib2.Http object. Only mocks out the request function. - - This mock keeps track of the last url, method and body called. - - Attributes: - response_success: Fake successful HTTP response. - response_failure: Fake failure HTTP response. - response: The response of the next HTTP request. - content: The content of the next HTTP request. - last_url: The last URL that an HTTP request was made to. - last_method: The last method that an HTTP request was made to. - last_body: The last body method that an HTTP request was made to. - - """ - response_success = {"status": httplib.OK} - response_failure = {"status": httplib.BAD_REQUEST} - - def __init__(self): - """Initialize the Http2Mock.""" - self.response = self.response_success - self.content = {} - self.last_url = None - self.last_method = None - self.last_body = None - - def request(self, url, method, headers=None, body=None): - """Makes a fake HTTP request. - - Args: - url: The url to make the call to. - method: The type of call. POST, GET, etc. - body: The request of the body. - - Returns: - A tuple of a response and its content. - """ - self.last_url = url - self.last_method = method - self.last_body = body - return (self.response, json.dumps(self.content)) - - -class TestGitHubService(unittest.TestCase): - """Tests for the GitHubService.""" - - def setUp(self): - self.http_mock = Http2Mock() - self.github_service = github_issue_converter.GitHubService( - GITHUB_USERNAME, GITHUB_REPO, GITHUB_TOKEN, - rate_limit=False, - http_instance=self.http_mock) - - def testSuccessfulRequestSuccess(self): - success = github_issue_converter._CheckSuccessful( - self.http_mock.response_success) - self.assertTrue(success) - - def testSuccessfulRequestFailure(self): - failure = github_issue_converter._CheckSuccessful( - self.http_mock.response_failure) - self.assertFalse(failure) - - def testGetRemainingRequestsRequestsLeft(self): - self.http_mock.content = {"rate": {"remaining": "500"}} - requests = self.github_service._GetRemainingRequests() - self.assertEqual(requests, 500) - - def testGetRemainingRequestsNoRequestsLeft(self): - self.http_mock.content = {"rate": {"remaining": "0"}} - requests = self.github_service._GetRemainingRequests() - self.assertEqual(requests, 0) - - def testGetRemainingRequestsBadResponse(self): - self.http_mock.content = {"bad": "content"} - requests = self.github_service._GetRemainingRequests() - self.assertEqual(requests, 0) - - def testRequestLimitReachedLimitReached(self): - self.http_mock.content = {"rate": {"remaining": "0"}} - limit_reached = self.github_service._RequestLimitReached() - self.assertTrue(limit_reached) - - def testRequestLimitReachedLimitNotReached(self): - self.http_mock.content = {"rate": {"remaining": "500"}} - limit_reached = self.github_service._RequestLimitReached() - self.assertFalse(limit_reached) - - def testHttpRequest(self): - response, content = self.github_service._PerformHttpRequest("GET", "/test") - self.assertEqual(response, self.http_mock.response_success) - self.assertEqual(content, {}) - self.assertEqual(self.http_mock.last_method, "GET") - uri = ("%s/test?access_token=%s" % (GITHUB_API_URL, GITHUB_TOKEN)) - self.assertEqual(self.http_mock.last_url, uri) - - def testHttpRequestParams(self): - params = {"one": 1, "two": 2} - response, content = self.github_service._PerformHttpRequest("POST", - "/test", - params=params) - self.assertEqual(response, self.http_mock.response_success) - self.assertEqual(content, {}) - self.assertEqual(self.http_mock.last_method, "POST") - - uri = ("%s/test?access_token=%s&one=1&two=2" % - (GITHUB_API_URL, GITHUB_TOKEN)) - # pylint: disable=unpacking-non-sequence - (expected_scheme, expected_domain, expected_path, expected_params, - expected_query, expected_fragment) = urlparse.urlparse(uri) - expected_query_list = expected_query.split("&") - - # pylint: disable=unpacking-non-sequence - (actual_scheme, actual_domain, actual_path, actual_params, actual_query, - actual_fragment) = urlparse.urlparse(self.http_mock.last_url) - actual_query_list = actual_query.split("&") - - self.assertEqual(expected_scheme, actual_scheme) - self.assertEqual(expected_domain, actual_domain) - self.assertEqual(expected_path, actual_path) - self.assertEqual(expected_params, actual_params) - self.assertEqual(expected_fragment, actual_fragment) - self.assertItemsEqual(expected_query_list, actual_query_list) - - def testGetRequest(self): - self.github_service.PerformGetRequest("/test") - self.assertEqual(self.http_mock.last_method, "GET") - - def testPostRequest(self): - self.github_service.PerformPostRequest("/test", "") - self.assertEqual(self.http_mock.last_method, "POST") - - def testPatchRequest(self): - self.github_service.PerformPatchRequest("/test", "") - self.assertEqual(self.http_mock.last_method, "PATCH") - - -class TestUserService(unittest.TestCase): - """Tests for the UserService.""" - - def setUp(self): - self.github_service = FakeGitHubService(GITHUB_USERNAME, - GITHUB_REPO, - GITHUB_TOKEN) - self.github_user_service = github_issue_converter.UserService( - self.github_service) - - def testIsUserTrue(self): - is_user = self.github_user_service.IsUser("username123") - self.assertTrue(is_user) - - def testIsUserFalse(self): - self.github_service.AddFailureResponse() - is_user = self.github_user_service.IsUser("username321") - self.assertFalse(is_user) - - -class TestIssueService(unittest.TestCase): - """Tests for the IssueService.""" - - def setUp(self): - self.http_mock = Http2Mock() - self.github_service = github_issue_converter.GitHubService( - GITHUB_USERNAME, GITHUB_REPO, GITHUB_TOKEN, - rate_limit=False, - http_instance=self.http_mock) - self.github_issue_service = github_issue_converter.IssueService( - self.github_service, comment_delay=0) - - def testCreateIssue(self): - issue_body = { - "body": ( - "```\none\n```\n\nOriginal issue reported on code.google.com by `a_uthor` on last year\n" - "- **Labels added**: added-label\n" - "- **Labels removed**: removed-label\n"), - "assignee": "default_username", - "labels": ["awesome", "great"], - "title": "issue_title", - } - self.http_mock.content = {"number": 1} - issue_number = self.github_issue_service.CreateIssue(SINGLE_ISSUE) - self.assertEqual(self.http_mock.last_method, "POST") - uri = ("%s/repos/%s/%s/issues?access_token=%s" % - (GITHUB_API_URL, GITHUB_USERNAME, GITHUB_REPO, GITHUB_TOKEN)) - self.assertEqual(self.http_mock.last_url, uri) - self.assertEqual(self.http_mock.last_body, json.dumps(issue_body)) - self.assertEqual(1, issue_number) - - def testCloseIssue(self): - self.github_issue_service.CloseIssue(123) - self.assertEqual(self.http_mock.last_method, "PATCH") - uri = ("%s/repos/%s/%s/issues/%d?access_token=%s" % - (GITHUB_API_URL, GITHUB_USERNAME, GITHUB_REPO, 123, GITHUB_TOKEN)) - self.assertEqual(self.http_mock.last_url, uri) - self.assertEqual(self.http_mock.last_body, - json.dumps({"state": "closed"})) - - def testCreateComment(self): - comment_body = ( - "```\none\n```\n\nOriginal issue reported on code.google.com " - "by `a_uthor` on last year\n" - "- **Labels added**: added-label\n" - "- **Labels removed**: removed-label\n") - self.github_issue_service.CreateComment( - 1, "1", SINGLE_COMMENT, GITHUB_REPO) - self.assertEqual(self.http_mock.last_method, "POST") - uri = ("%s/repos/%s/%s/issues/%d/comments?access_token=%s" % - (GITHUB_API_URL, GITHUB_USERNAME, GITHUB_REPO, 1, GITHUB_TOKEN)) - self.assertEqual(self.http_mock.last_url, uri) - self.assertEqual(self.http_mock.last_body, - json.dumps({"body": comment_body})) - - def testGetIssueNumber(self): - issue = {"number": 1347} - issue_number = self.github_issue_service._GetIssueNumber(issue) - self.assertEqual(1347, issue_number) - - def testGetIssues(self): - fake_github_service = FakeGitHubService(GITHUB_USERNAME, - GITHUB_REPO, - GITHUB_TOKEN) - github_issue_service = github_issue_converter.IssueService( - fake_github_service, comment_delay=0) - fake_github_service.AddFailureResponse() - with self.assertRaises(IOError): - github_issue_service.GetIssues() - - -class TestIssueExporter(unittest.TestCase): - """Tests for the IssueService.""" - - def setUp(self): - self.github_service = FakeGitHubService(GITHUB_USERNAME, - GITHUB_REPO, - GITHUB_TOKEN) - self.github_user_service = github_issue_converter.UserService( - self.github_service) - self.github_issue_service = github_issue_converter.IssueService( - self.github_service, comment_delay=0) - self.issue_exporter = issues.IssueExporter( - self.github_issue_service, self.github_user_service, - NO_ISSUE_DATA, GITHUB_REPO, USER_MAP) - self.issue_exporter.Init() - - self.TEST_ISSUE_DATA = [ - { - "id": "1", - "number": "1", - "title": "Title1", - "state": "open", - "comments": { - "items": [COMMENT_ONE, COMMENT_TWO, COMMENT_THREE], - }, - "labels": ["Type-Issue", "Priority-High"], - "owner": {"kind": "projecthosting#issuePerson", - "name": "User1" - }, - }, - { - "id": "2", - "number": "2", - "title": "Title2", - "state": "closed", - "owner": {"kind": "projecthosting#issuePerson", - "name": "User2" - }, - "labels": [], - "comments": { - "items": [COMMENT_ONE], - }, - }, - { - "id": "3", - "number": "3", - "title": "Title3", - "state": "closed", - "comments": { - "items": [COMMENT_ONE, COMMENT_TWO], - }, - "labels": ["Type-Defect"], - "owner": {"kind": "projecthosting#issuePerson", - "name": "User3" - } - }] - - - def testGetAllPreviousIssues(self): - self.assertEqual(0, len(self.issue_exporter._previously_created_issues)) - content = [{"number": 1, "title": "issue_title", "comments": 2}] - self.github_service.AddResponse(content=content) - self.issue_exporter._GetAllPreviousIssues() - self.assertEqual(1, len(self.issue_exporter._previously_created_issues)) - self.assertTrue(1 in self.issue_exporter._previously_created_issues) - self.assertEqual("issue_title", - self.issue_exporter._previously_created_issues[1]["title"]) - self.assertEqual(2, - self.issue_exporter._previously_created_issues[1]["comment_count"]) - - def testCreateIssue(self): - content = {"number": 1234} - self.github_service.AddResponse(content=content) - - issue_number = self.issue_exporter._CreateIssue(SINGLE_ISSUE) - self.assertEqual(1234, issue_number) - - def testCreateIssueFailedOpenRequest(self): - self.github_service.AddFailureResponse() - with self.assertRaises(issues.ServiceError): - self.issue_exporter._CreateIssue(SINGLE_ISSUE) - - def testCreateIssueFailedCloseRequest(self): - content = {"number": 1234} - self.github_service.AddResponse(content=content) - self.github_service.AddFailureResponse() - issue_number = self.issue_exporter._CreateIssue(SINGLE_ISSUE) - self.assertEqual(1234, issue_number) - - def testCreateComments(self): - self.assertEqual(0, self.issue_exporter._comment_number) - self.issue_exporter._CreateComments(COMMENTS_DATA, 1234, SINGLE_ISSUE) - self.assertEqual(4, self.issue_exporter._comment_number) - - def testCreateCommentsFailure(self): - self.github_service.AddFailureResponse() - self.assertEqual(0, self.issue_exporter._comment_number) - with self.assertRaises(issues.ServiceError): - self.issue_exporter._CreateComments(COMMENTS_DATA, 1234, SINGLE_ISSUE) - - def testStart(self): - self.issue_exporter._issue_json_data = self.TEST_ISSUE_DATA - - # Note: Some responses are from CreateIssues, others are from CreateComment. - self.github_service.AddResponse(content={"number": 1}) - self.github_service.AddResponse(content={"number": 10}) - self.github_service.AddResponse(content={"number": 11}) - self.github_service.AddResponse(content={"number": 2}) - self.github_service.AddResponse(content={"number": 20}) - self.github_service.AddResponse(content={"number": 3}) - self.github_service.AddResponse(content={"number": 30}) - - self.issue_exporter.Start() - - self.assertEqual(3, self.issue_exporter._issue_total) - self.assertEqual(3, self.issue_exporter._issue_number) - # Comment counts are per issue and should match the numbers from the last - # issue created, minus one for the first comment, which is really - # the issue description. - self.assertEqual(1, self.issue_exporter._comment_number) - self.assertEqual(1, self.issue_exporter._comment_total) - - def testStart_SkipAlreadyCreatedIssues(self): - self.issue_exporter._previously_created_issues["1"] = { - "title": "Title1", - "comment_count": 3 - } - self.issue_exporter._previously_created_issues["2"] = { - "title": "Title2", - "comment_count": 1 - } - self.issue_exporter._issue_json_data = self.TEST_ISSUE_DATA - - self.github_service.AddResponse(content={"number": 3}) - - self.issue_exporter.Start() - - self.assertEqual(2, self.issue_exporter._skipped_issues) - self.assertEqual(3, self.issue_exporter._issue_total) - self.assertEqual(3, self.issue_exporter._issue_number) - - def testStart_ReAddMissedComments(self): - self.issue_exporter._previously_created_issues["1"] = { - "title": "Title1", - "comment_count": 1 # Missing 2 comments. - } - self.issue_exporter._issue_json_data = self.TEST_ISSUE_DATA - - # First requests to re-add comments, then create issues. - self.github_service.AddResponse(content={"number": 11}) - - self.github_service.AddResponse(content={"number": 2}) - self.github_service.AddResponse(content={"number": 20}) - self.github_service.AddResponse(content={"number": 3}) - self.github_service.AddResponse(content={"number": 30}) - - self.issue_exporter.Start() - self.assertEqual(1, self.issue_exporter._skipped_issues) - self.assertEqual(3, self.issue_exporter._issue_total) - self.assertEqual(3, self.issue_exporter._issue_number) - - - def testStart_GetErrorIfGoogleCodeAndGitHubDoNotMatch(self): - self.issue_exporter._previously_created_issues["1"] = { - "title": "Title1"} - self.issue_exporter._previously_created_issues["2"] = { - "title": "< not issue #2's title >"} - self.issue_exporter._issue_json_data = self.TEST_ISSUE_DATA - - with self.assertRaises(RuntimeError): - self.issue_exporter.Start() - - def testStart_GetErrorIfCreatedGitHubIDDoesNotMatch(self): - self.issue_exporter._issue_json_data = self.TEST_ISSUE_DATA - - # Note: Some responses are from CreateIssues, others are from CreateComment. - self.github_service.AddResponse(content={"number": 1}) - self.github_service.AddResponse(content={"number": 10}) - self.github_service.AddResponse(content={"number": 11}) - self.github_service.AddResponse(content={"number": 3}) # Expects next issue ID 2. - - with self.assertRaises(RuntimeError): - self.issue_exporter.Start() - - -if __name__ == "__main__": - unittest.main(buffer=True) diff --git a/googlecode-issues-exporter/issues.py b/googlecode-issues-exporter/issues.py deleted file mode 100644 index fd498bc..0000000 --- a/googlecode-issues-exporter/issues.py +++ /dev/null @@ -1,700 +0,0 @@ -# Copyright 2014 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tool for uploading Google Code issues to an issue service. -""" - -import collections -import datetime -import json -import re -import sys - - -class IdentityDict(dict): - def __missing__(self, key): - return key - - -def TryFormatDate(date): - """Attempt to clean up a timestamp date.""" - try: - if date.endswith(":"): - date = date[:len(date) - 1] - datetime_version = datetime.datetime.strptime( - date, "%Y-%m-%dT%H:%M:%S.%fZ") - return str(datetime_version) - except ValueError as ve: - return date - - -def WrapText(text, max): - """Inserts a newline if any line of a file is > max chars. - - Note that the newline is inserted at the first whitespace - character, so there may be lines longer than max. - """ - char_list = list(text) - last_linebreak = 0 - for i in range(0, len(char_list)): - if char_list[i] == '\n': - last_linebreak = i - if i - last_linebreak > max and char_list[i] == ' ': - # Replace ' ' with '\n' - char_list.pop(i) - char_list.insert(i, '\n') - last_linebreak = i - return ''.join(char_list) - - -class Error(Exception): - """Base error class.""" - - -class InvalidUserError(Error): - """Error for an invalid user.""" - - -class ProjectNotFoundError(Error): - """Error for a non-existent project.""" - - -class ServiceError(Error): - """Error when communicating with the issue or user service.""" - - -class UserService(object): - """Abstract user operations. - - Handles user operations on an user API. - """ - - def IsUser(self, username): - """Checks if the user exists. - - Args: - username: The username to check. - - Returns: - True if the username exists. - """ - raise NotImplementedError() - - -class GoogleCodeIssue(object): - """Google Code issue. - - Handles parsing and viewing a Google Code issue. - """ - - def __init__(self, issue, project_name, user_map): - """Initialize the GoogleCodeIssue. - - Args: - issue: The Google Code Issue as a dictionary. - project_name: The name of the project the issue belongs to. - user_map: A map from Google Code usernames to issue service names. - """ - self._issue = issue - self._project_name = project_name - self._user_map = user_map - - def GetProjectName(self): - """Returns the project name.""" - return self._project_name - - def GetUserMap(self): - """Returns the user map.""" - return self._user_map - - def GetOwner(self): - """Get the owner username of a Google Code issue. - - This will ALWAYS be the person requesting the issue export. - """ - return self._user_map["user_requesting_export"] - - def GetContentUpdatedOn(self): - """Get the date the content was last updated from a Google Code issue. - - Returns: - The time stamp when the issue content was last updated - """ - return self._issue["updated"] - - def GetCreatedOn(self): - """Get the creation date from a Google Code issue. - - Returns: - The time stamp when the issue content was created - """ - return self._issue["published"] - - def GetId(self): - """Get the id from a Google Code issue. - - Returns: - The issue id - """ - return self._issue["id"] - - def GetLabels(self): - """Get the labels from a Google Code issue. - - Returns: - A list of the labels of this issue. - """ - return self._issue.get("labels", []) - - def GetKind(self): - """Get the kind from a Google Code issue. - - Returns: - The issue kind, if none is found defaults to 'Defect' - """ - types = [t for t in self.GetLabels() if "Type-" in t] - if types: - return types[0][len("Type-"):] - return "Defect" - - def GetPriority(self): - """Get the priority from a Google Code issue. - - Returns: - The issue priority, if none is found defaults to 'Medium' - """ - priorities = [p for p in self.GetLabels() if "Priority-" in p] - if priorities: - return priorities[0][len("Priority-"):] - return "Medium" - - def GetAuthor(self): - """Get the author's username of a Google Code issue. - - Returns: - The Google Code username that the issue is authored by or the - repository owner if no mapping or email address exists. - """ - if "author" not in self._issue: - return None - - author = self._issue["author"]["name"] - return self._user_map[author] - - def GetStatus(self): - """Get the status from a Google Code issue. - - Returns: - The issue status - """ - status = self._issue["status"].lower() - if status == "accepted": - status = "open" - return status - - def GetTitle(self): - """Get the title from a Google Code issue. - - Returns: - The issue title - """ - return self._issue["title"] - - def GetUpdatedOn(self): - """Get the date the issue was last updated. - - Returns: - The time stamp when the issue was last updated - """ - return self.GetCreatedOn() - - def _GetDescription(self): - """Returns the raw description of the issue. - - Returns: - The raw issue description as a comment. - """ - return self._issue["comments"]["items"][0] - - def GetComments(self): - """Get the list of comments for the issue (if any). - - Returns: - The list of comments attached to the issue - """ - return self._issue["comments"]["items"][1:] - - def IsOpen(self): - """Check if an issue is marked as open. - - Returns: - True if the issue was open. - """ - return "state" in self._issue and self._issue["state"] == "open" - - def GetDescription(self): - """Returns the Description of the issue.""" - # Just return the description of the underlying comment. - googlecode_comment = GoogleCodeComment(self, self._GetDescription()) - return googlecode_comment.GetDescription() - - -class GoogleCodeComment(object): - """Google Code Comment. - - Handles parsing and viewing a Google Code Comment. - """ - - def __init__(self, googlecode_issue, comment): - """Initialize the GoogleCodeComment. - - Args: - googlecode_issue: A GoogleCodeIssue instance. - comment: The Google Code Comment as dictionary. - """ - self._comment = comment - self._googlecode_issue = googlecode_issue - - def GetContent(self): - """Get the content from a Google Code comment. - - Returns: - The issue comment - """ - return self._comment["content"] - - def GetCreatedOn(self): - """Get the creation date from a Google Code comment. - - Returns: - The time stamp when the issue comment content was created - """ - return self._comment["published"] - - def GetId(self): - """Get the id from a Google Code comment. - - Returns: - The issue comment id - """ - return self._comment["id"] - - def GetLabels(self): - """Get the labels modified with the comment.""" - if "updates" in self._comment: - if "labels" in self._comment["updates"]: - return self._comment["updates"]["labels"] - return [] - - def GetIssue(self): - """Get the GoogleCodeIssue this comment belongs to. - - Returns: - The issue id - """ - return self._googlecode_issue - - def GetUpdatedOn(self): - """Get the date the issue comment content was last updated. - - Returns: - The time stamp when the issue comment content was last updated - """ - return self.GetCreatedOn() - - def GetAuthor(self): - """Get the author's username of a Google Code issue comment. - - Returns: - The Google Code username that the issue comment is authored by or the - repository owner if no mapping or email address exists. - """ - if "author" not in self._comment: - return None - - author = self._comment["author"]["name"] - return self.GetIssue().GetUserMap()[author] - - def GetDescription(self): - """Returns the Description of the comment.""" - author = self.GetAuthor() - comment_date = self.GetCreatedOn() - comment_text = self.GetContent() - - if not comment_text: - comment_text = "(No text was entered with this change)" - - # Remove tags, which Codesite automatically includes if issue body is - # based on a prompt. - # TODO(chrsmith): Unescample HTML. e.g. > and á - comment_text = comment_text.replace("", "") - comment_text = comment_text.replace("", "") - comment_text = WrapText(comment_text, 82) # In case it was already wrapped... - - body = "```\n" + comment_text + "\n```" - - footer = "\n\nOriginal issue reported on code.google.com by `%s` on %s" % ( - author, TryFormatDate(comment_date)) - - # Add label adjustments. - if self.GetLabels(): - labels_added = [] - labels_removed = [] - for label in self.GetLabels(): - if label.startswith("-"): - labels_removed.append(label[1:]) - else: - labels_added.append(label) - - footer += "\n" - if labels_added: - footer += "- **Labels added**: %s\n" % (", ".join(labels_added)) - if labels_removed: - footer += "- **Labels removed**: %s\n" % (", ".join(labels_removed)) - - # Add references to attachments as appropriate. - attachmentLines = [] - for attachment in self._comment["attachments"] if "attachments" in self._comment else []: - if "isDeleted" in attachment: - # Deleted attachments won't be found on the issue mirror. - continue - - link = "https://storage.googleapis.com/google-code-attachments/%s/issue-%d/comment-%d/%s" % ( - self.GetIssue().GetProjectName(), self.GetIssue().GetId(), - self.GetId(), attachment["fileName"]) - - def has_extension(extension): - return attachment["fileName"].lower().endswith(extension) - - is_image_attachment = False - for extension in [".png", ".jpg", ".jpeg", ".bmp", ".tif", ".gif"]: - is_image_attachment |= has_extension(".png") - - if is_image_attachment: - line = " * *Attachment: %s
![%s](%s)*" % ( - attachment["fileName"], attachment["fileName"], link) - else: - line = " * *Attachment: [%s](%s)*" % (attachment["fileName"], link) - attachmentLines.append(line) - - if len(attachmentLines) > 0: - footer += "\n
\n" + "\n".join(attachmentLines) - - # Return the data to send to generate the comment. - return body + footer - - -class IssueService(object): - """Abstract issue operations. - - Handles creating and updating issues and comments on an user API. - """ - - def GetIssues(self, state="open"): - """Gets all of the issue for the repository. - - Args: - state: The state of the repository can be either 'open' or 'closed'. - - Returns: - The list of all of the issues for the given repository. - - Raises: - IOError: An error occurred accessing previously created issues. - """ - raise NotImplementedError() - - def CreateIssue(self, googlecode_issue): - """Creates an issue. - - Args: - googlecode_issue: An instance of GoogleCodeIssue - - Returns: - The issue number of the new issue. - - Raises: - ServiceError: An error occurred creating the issue. - """ - raise NotImplementedError() - - def CloseIssue(self, issue_number): - """Closes an issue. - - Args: - issue_number: The issue number. - """ - raise NotImplementedError() - - def CreateComment(self, issue_number, source_issue_id, - googlecode_comment, project_name): - """Creates a comment on an issue. - - Args: - issue_number: The issue number. - source_issue_id: The Google Code issue id. - googlecode_comment: An instance of GoogleCodeComment - project_name: The Google Code project name. - """ - raise NotImplementedError() - - -def LoadIssueData(issue_file_path, project_name): - """Loads issue data from a file. - - Args: - issue_file_path: path to the file to load - project_name: name of the project to load - - Returns: - Issue data as a list of dictionaries. - - Raises: - ProjectNotFoundError: the project_name was not found in the file. - """ - with open(issue_file_path) as user_file: - user_data = json.load(user_file) - user_projects = user_data["projects"] - - for project in user_projects: - if project_name == project["name"]: - return project["issues"]["items"] - - raise ProjectNotFoundError("Project %s not found" % project_name) - - -def LoadUserData(user_file_path, user_service): - """Loads user data from a file. If not present, the user name will - just return whatever is passed to it. - - Args: - user_file_path: path to the file to load - user_service: an instance of UserService - """ - identity_dict = IdentityDict() - if not user_file_path: - return identity_dict - - with open(user_file_path) as user_data: - user_json = user_data.read() - - user_map = json.loads(user_json)["users"] - for username in user_map.values(): - if not user_service.IsUser(username): - raise InvalidUserError("%s is not a User" % username) - - result.update(user_map) - return result - - -class IssueExporter(object): - """Issue Migration. - - Handles the uploading issues from Google Code to an issue service. - """ - - def __init__(self, issue_service, user_service, issue_json_data, - project_name, user_map): - """Initialize the IssueExporter. - - Args: - issue_service: An instance of IssueService. - user_service: An instance of UserService. - project_name: The name of the project to export to. - issue_json_data: A data object of issues from Google Code. - user_map: A map from user email addresses to service usernames. - """ - self._issue_service = issue_service - self._user_service = user_service - self._issue_json_data = issue_json_data - self._project_name = project_name - self._user_map = user_map - - # Mapping from issue ID to the issue's metadata. This is used to verify - # consistency with an previous attempts at exporting issues. - self._previously_created_issues = {} - - self._issue_total = 0 - self._issue_number = 0 - self._comment_number = 0 - self._comment_total = 0 - self._skipped_issues = 0 - - def Init(self): - """Initialize the needed variables.""" - self._GetAllPreviousIssues() - - def _GetAllPreviousIssues(self): - """Gets all previously uploaded issues.""" - print "Getting any previously added issues..." - open_issues = self._issue_service.GetIssues("open") - closed_issues = self._issue_service.GetIssues("closed") - issues = open_issues + closed_issues - for issue in issues: - # Yes, GitHub's issues API has both ID and Number, and they are - # the opposite of what you think they are. - issue["number"] not in self._previously_created_issues or die( - "GitHub returned multiple issues with the same ID?") - self._previously_created_issues[issue["number"]] = { - "title": issue["title"], - "comment_count": issue["comments"], - } - - def _UpdateProgressBar(self): - """Update issue count 'feed'. - - This displays the current status of the script to the user. - """ - feed_string = ("\rIssue: %d/%d -> Comment: %d/%d " % - (self._issue_number, self._issue_total, - self._comment_number, self._comment_total)) - sys.stdout.write(feed_string) - sys.stdout.flush() - - def _CreateIssue(self, googlecode_issue): - """Converts an issue from Google Code to an issue service. - - This will take the Google Code issue and create a corresponding issue on - the issue service. If the issue on Google Code was closed it will also - be closed on the issue service. - - Args: - googlecode_issue: An instance of GoogleCodeIssue - - Returns: - The issue number assigned by the service. - """ - return self._issue_service.CreateIssue(googlecode_issue) - - def _CreateComments(self, comments, issue_number, googlecode_issue): - """Converts a list of issue comment from Google Code to an issue service. - - This will take a list of Google Code issue comments and create - corresponding comments on an issue service for the given issue number. - - Args: - comments: A list of comments (each comment is just a string). - issue_number: The issue number. - source_issue_id: The Google Code issue id. - """ - self._comment_total = len(comments) - self._comment_number = 0 - - for comment in comments: - googlecode_comment = GoogleCodeComment(googlecode_issue, comment) - self._comment_number += 1 - self._UpdateProgressBar() - self._issue_service.CreateComment(issue_number, - googlecode_issue.GetId(), - googlecode_comment, - self._project_name) - - def Start(self): - """The primary function that runs this script. - - This will traverse the issues and attempt to create each issue and its - comments. - """ - print "Starting issue export for '%s'" % (self._project_name) - - # If there are existing issues, then confirm they exactly match the Google - # Code issues. Otherwise issue IDs will not match and/or there may be - # missing data. - self._AssertInGoodState() - - self._issue_total = len(self._issue_json_data) - self._issue_number = 0 - self._skipped_issues = 0 - for issue in self._issue_json_data: - googlecode_issue = GoogleCodeIssue( - issue, self._project_name, self._user_map) - - self._issue_number += 1 - self._UpdateProgressBar() - - issue_id = googlecode_issue.GetId() - if issue_id in self._previously_created_issues: - self._skipped_issues += 1 - continue - - issue_number = self._CreateIssue(googlecode_issue) - if issue_number < 0: - continue - if int(issue_number) != int(googlecode_issue.GetId()): - raise RuntimeError("Google Code and GitHub issue nos mismatch at #%s (got %s)" % ( - googlecode_issue.GetId(), issue_number)) - - comments = googlecode_issue.GetComments() - self._CreateComments(comments, issue_number, googlecode_issue) - - if not googlecode_issue.IsOpen(): - self._issue_service.CloseIssue(issue_number) - - # TODO(chrsmith): Issue a warning if/when the issue ID get out of sync. - if self._skipped_issues > 0: - print ("\nSkipped %d/%d issue previously uploaded." % - (self._skipped_issues, self._issue_total)) - - def _AssertInGoodState(self): - """Checks if the last issue exported is sound, otherwise raises an error. - - Checks the existing issues that have been exported and confirms that it - matches the issue on Google Code. (Both Title and ID match.) It then - confirms that it has all of the expected comments, adding any missing ones - as necessary. - """ - if len(self._previously_created_issues) == 0: - return - - print ("Existing issues detected for the repo. Likely due to a previous\n" - " run being aborted or killed. Checking consistency...") - - # Get the last exported issue, and its dual on Google Code. - last_gh_issue_id = -1 - for id in self._previously_created_issues: - if id > last_gh_issue_id: - last_gh_issue_id = id - last_gh_issue = self._previously_created_issues[last_gh_issue_id] - - last_gc_issue = None - for issue in self._issue_json_data: - if int(issue["id"]) == int(last_gh_issue_id) and ( - issue["title"] == last_gh_issue["title"]): - last_gc_issue = GoogleCodeIssue(issue, - self._project_name, - self._user_map) - break - - if last_gc_issue is None: - raise RuntimeError( - "Unable to find Google Code issue #%s '%s'.\n" - " Were issues added to GitHub since last export attempt?" % ( - last_gh_issue_id, last_gh_issue["title"])) - - print "Last issue (#%s) matches. Checking comments..." % (last_gh_issue_id) - - # Check comments. Add any missing ones as needed. - num_gc_issue_comments = len(last_gc_issue.GetComments()) - if last_gh_issue["comment_count"] != num_gc_issue_comments: - print "GitHub issue has fewer comments than Google Code's. Fixng..." - for idx in range(last_gh_issue["comment_count"], num_gc_issue_comments): - comment = last_gc_issue.GetComments()[idx] - googlecode_comment = GoogleCodeComment(last_gc_issue, comment) - # issue_number == source_issue_id - self._issue_service.CreateComment( - int(last_gc_issue.GetId()), int(last_gc_issue.GetId()), - googlecode_comment, self._project_name) - print " Added comment #%s." % (idx + 1) - - print "Done! Issue tracker now in expected state. Ready for more exports." diff --git a/googlecode-issues-exporter/issues_test.py b/googlecode-issues-exporter/issues_test.py deleted file mode 100644 index 74278a9..0000000 --- a/googlecode-issues-exporter/issues_test.py +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright 2015 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for issues.""" - -# pylint: disable=missing-docstring,protected-access - -import collections -import copy -import unittest - -import issues - - -DEFAULT_USERNAME = "default_username" -REPO = "repo" - -USER_MAP = collections.defaultdict(lambda: DEFAULT_USERNAME) -USER_MAP.update({ - "user@email.com": "a_uthor", - "user2@gmail.com": "w_riter", -}) - -# Empty issue data map -NO_ISSUE_DATA = {} - -COMMENT_ONE = { - "content": "one", - "id": 1, - "published": "last year", - "author": {"name": "user@email.com"}, - "updates": { - "labels": ["added-label", "-removed-label"], - }, -} -COMMENT_TWO = { - "content": "two", - "id": 2, - "published": "last week", - "author": {"name": "user2@gmail.com"}, -} -COMMENT_THREE = { - "content": "three", - "id": 3, - "published": "yesterday", - "author": {"name": "unknown@example.com"}, -} -COMMENTS_DATA = [ - COMMENT_ONE, - {"content": "two", "id": 2, "published": "last week"}, - {"content": "three", "id": 3, "published": "yesterday"}, - {"content": "four", "id": 4, "published": "today"}, -] -# Full issue json -ISSUE_JSON = { - "id": 1, - "state": "closed", - "title": "issue_title", - "comments": {"items": [COMMENT_ONE]}, - "labels": ["awesome", "great"], - "published": "last year", - "updated": "last month", - "status": "Fixed", - "owner": { - "kind": "projecthosting#issuePerson", - "name": "user@email.com", - }, -} - -SINGLE_ISSUE = issues.GoogleCodeIssue(ISSUE_JSON, REPO, USER_MAP) - -SINGLE_COMMENT = issues.GoogleCodeComment(SINGLE_ISSUE, COMMENT_ONE) - - -class GoogleCodeIssueTest(unittest.TestCase): - """Tests for GoogleCodeIssue.""" - - def testGetIssueOwner(self): - # Report all issues coming from the person who initiated the - # export. - self.assertEqual("default_username", SINGLE_ISSUE.GetOwner()) - - def testGetIssueOwnerNoOwner(self): - issue_json = ISSUE_JSON.copy() - del issue_json["owner"] - issue = issues.GoogleCodeIssue(issue_json, REPO, USER_MAP) - self.assertEqual("default_username", issue.GetOwner()) - - def testGetIssueUserOwner(self): - issue_json = copy.deepcopy(ISSUE_JSON) - issue_json["owner"]["name"] = "notauser@email.com" - issue = issues.GoogleCodeIssue( - issue_json, REPO, USER_MAP) - self.assertEqual(DEFAULT_USERNAME, issue.GetOwner()) - - def testGetCommentAuthor(self): - self.assertEqual("a_uthor", SINGLE_COMMENT.GetAuthor()) - - def testGetCommentDescription(self): - self.assertEqual( - "```\none\n```\n\nOriginal issue reported on code.google.com by " - "`a_uthor` on last year\n" - "- **Labels added**: added-label\n" - "- **Labels removed**: removed-label\n", - SINGLE_COMMENT.GetDescription()) - - def testTryFormatDate(self): - self.assertEqual("last year", issues.TryFormatDate("last year")) - self.assertEqual("2007-02-03 05:58:17", - issues.TryFormatDate("2007-02-03T05:58:17.000Z:")) - self.assertEqual("2014-01-05 04:43:15", - issues.TryFormatDate("2014-01-05T04:43:15.000Z")) - - def testWrapText(self): - self.assertEqual(issues.WrapText("0123456789", 3), - "0123456789") - self.assertEqual(issues.WrapText("01234 56789", 3), - "01234\n56789") - self.assertEqual(issues.WrapText("a b c d e f g h", 4), - "a b c\nd e f\ng h") - - def testLoadUserData(self): - # Verify the "identity dictionary" behavior. - user_data_dict = issues.LoadUserData(None, None) - self.assertEqual(user_data_dict["chrs...@goog.com"], "chrs...@goog.com") - - -if __name__ == "__main__": - unittest.main(buffer=True) diff --git a/googlecode-issues-exporter/pylintrc b/googlecode-issues-exporter/pylintrc deleted file mode 100644 index db9ff56..0000000 --- a/googlecode-issues-exporter/pylintrc +++ /dev/null @@ -1,20 +0,0 @@ -[MESSAGES CONTROL] - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -disable=invalid-name,too-few-public-methods,too-many-arguments,no-self-use,too-many-locals,too-many-instance-attributes,abstract-class-little-used,duplicate-code,too-many-public-methods,locally-disabled - -[FORMAT] -indent-string=' ' - -[REPORTS] - -# Tells whether to display a full report or only the messages -reports=no diff --git a/wiki_to_md/convert-repo.sh b/wiki_to_md/convert-repo.sh deleted file mode 100755 index 95098fa..0000000 --- a/wiki_to_md/convert-repo.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash - -# Converts Google Code wiki pages to GitHub flavored Markdown. This is done -# inside of an existing git repo, and the process will build up a series -# of git commits for each file modified. -USAGE="Bulk converter for wiki pages. - -convert-repo.sh -" - -if [ $# -eq 0 ] ; then - echo "$USAGE" - exit 1 -fi - -PATH_TO_WIKI2GMF=$1 -GIT_REPO_ROOT=$2 - -for wikifile in `find "$GIT_REPO_ROOT" -name "*.wiki"` -do - mdfile="`dirname $wikifile`/`basename $wikifile .wiki`.md" - - printf "**************************\n" - printf "Converting wiki: $file\n" - printf "To Markdown : $mdfile\n" - printf "**************************\n" - - python $PATH_TO_WIKI2GMF \ - --input_file=$wikifile \ - --output_file=$mdfile - - git rm $wikifile - git add $mdfile - git commit -m "Converted `basename $mdfile`" - - printf "done\n\n" -done diff --git a/wiki_to_md/example.md b/wiki_to_md/example.md deleted file mode 100644 index 38f497b..0000000 --- a/wiki_to_md/example.md +++ /dev/null @@ -1,295 +0,0 @@ -# Header1 - -This is a test file for verifying the tool's output. You can regenerate -`example.md` yourself by running: - -``` -python wiki2gfm.py \ - --project=test \ - --wikipages_list="TestPage" \ - --input_file=example.wiki \ - --output_file=example.md -``` - -Note that this is used by {{wiki2gfm\_test.py}}, so changing the -arguments will break unit tests. - - - -#### Tables (mistmatched header sides) - -Paragraph. - -More paragraphs. - -Tables: - -|**Name/Sample** | **Markup** | -|:-----------------|:-----------------| -| _italic_ | `_italic_` | -| **bold** | `*bold*` | -| `code` | ```code``` | -| `code` | `{{{code}}}` | -| superscript | `^super^script` | -| subscript | `,,sub,,script` | -| ~~strikeout~~ | `~~strikeout~~` | - -You can mix these typefaces in some ways: - -| **Markup** | **Result** | -|:------------------------------------|:----------------------------------| -| `_*bold* in italics_` | _**bold** in italics_ | -| `*_italics_ in bold*` | **_italics_ in bold** | -| `*~~strike~~ works too*` | **~~strike~~ works too** | -| `~~as well as _this_ way round~~` | ~~as well as _this_ way round~~ | - -**IN HTML** - - -Tables:
-
- - - - - - - -
Name/Sample Markup
italic _italic_
bold *bold*
code `code`
code {{{code}}}
superscript ^super^script
subscript ,,sub,,script
strikeout ~~strikeout~~
- -You can mix these typefaces in some ways:
-
- - - - - -
Markup Result
_*bold* in italics_ bold in italics
*_italics_ in bold* italics in bold
*~~strike~~ works too* strike works too
~~as well as _this_ way round~~ as well as this way round
- -#### Code (mismatched header sides again) - -``` -{{{ -def fib(n): - if n == 0 or n == 1: - return n - else: - # This recursion is not good for large numbers. - return fib(n-1) + fib(n-2) -}}} -``` - -Which results in: - -``` -def fib(n): - if n == 0 or n == 1: - return n - else: - # This recursion is not good for large numbers. - return fib(n-1) + fib(n-2) -``` - -``` - - - -``` - -```xml - - -``` - -**IN HTML** - - -
{{{
-def fib(n):
- if n == 0 or n == 1:
- return n
- else:
- # This recursion is not good for large numbers.
- return fib(n-1) + fib(n-2)
-}}}
-
- -Which results in:
-
-
def fib(n):
- if n == 0 or n == 1:
- return n
- else:
- # This recursion is not good for large numbers.
- return fib(n-1) + fib(n-2)
-
- -
<code language="xml">
-<hello target="world"/>
-</code>
-
- -

-<hello target="world"/>
-
-
- -==== Lists - -The following is: - * A list - * Of bulleted items - 1. This is a numbered sublist - 1. Which is done by indenting further - * And back to the main bulleted list - - * This is also a list - * With a single leading space - * Notice that it is rendered - 1. At the same levels - 1. As the above lists. - * Despite the different indentation levels. - -> Blockquotes are seen as lists. Time to nest: -> > Nested! - -> Okay back. - -**IN HTML** - - -The following is:
-
  • A list
    -
  • Of bulleted items
    -
    1. This is a numbered sublist
      -
    2. Which is done by indenting further
      -
  • And back to the main bulleted list
- -
  • This is also a list
    -
  • With a single leading space
    -
  • Notice that it is rendered
    -
    1. At the same levels
      -
    2. As the above lists.
      -
  • Despite the different indentation levels.
- -
Blockquotes are seen as lists. Time to nest:
-
Nested!
-
Okay back.
-
- -==== Links - -A LittleLink[?](TestPage.md) - -[TestPage](TestPage.md) is linked automatically. - -http://www.google.com/ - -[Google home page](http://www.google.com) - -[![](https://www.google.com/images/srpr/logo11w.png)](http://www.google.com) - -![https://www.google.com/images/srpr/logo11w.png](https://www.google.com/images/srpr/logo11w.png) - -[An image](https://www.google.com/images/srpr/logo11w.png) - -![![](https://www.google.com/images/srpr/logo11w.png)](https://www.google.com/images/srpr/logo11w.png) - -**IN HTML** - - -A LittleLink? - -TestPage is linked automatically.
-
-http://www.google.com/ - -Google home page - - - - - -An image - - -
- -==== Issues - -This is [issue 123](https://code.google.com/p/test/issues/detail?id=123), auto-linked. -This would be [issue 456](https://code.google.com/p/test/issues/detail?id=456), but must link to old one. - -**IN HTML** - -This is [issue 123](https://code.google.com/p/test/issues/detail?id=123), auto-linked. -This would be [issue 456](https://code.google.com/p/test/issues/detail?id=456), but must link to old one. - -==== Revisions - -[Revision 111605](https://code.google.com/p/test/source/detail?r=111605). - -rev111612. - -**IN HTML** - - -Revision 111605.
-
-rev111612.
-
- -==== Plugins - - - - - - - - -
-
-
-
-
-
- -==== Variables - -%%notdefined%% - -(TODO: Replace with username.) - -(TODO: Replace with email address.) - -test - -**IN HTML** (with additional variable magic) - - -%%notdefined%%
-
-(TODO: Replace with username.)
-
-(TODO: Replace with email address.)
-
-test
-
-this is a var!
-
- - -## All done! - -Hope you enjoyed. - -# Regressions - -We were adding extra spaces around tick marks: - -alpha `beta` gamma diff --git a/wiki_to_md/example.wiki b/wiki_to_md/example.wiki deleted file mode 100644 index d647328..0000000 --- a/wiki_to_md/example.wiki +++ /dev/null @@ -1,298 +0,0 @@ -#summary Summary Pragma. -#sidebar SidebarPage -#labels Ignored. -= Header1 = - -This is a test file for verifying the tool's output. You can regenerate -{{{example.md}}} yourself by running: - -{{{ -python wiki2gfm.py \ - --project=test \ - --wikipages_list="TestPage" \ - --input_file=example.wiki \ - --output_file=example.md -}}} - -Note that this is used by {{wiki2gfm_test.py}}, so changing the -arguments will break unit tests. - - - -==== Tables (mistmatched header sides) == - -Paragraph. - -More paragraphs. - -Tables: - -||* Name/Sample* || * Markup * || -|| _italic_ || `_italic_` || -|| *bold* || `*bold*` || -|| `code` || {{{`code`}}} || -|| {{{code}}} || `{{{code}}}` || -|| ^super^script || `^super^script` || -|| ,,sub,,script || `,,sub,,script` || -|| ~~strikeout~~ || `~~strikeout~~` || - -You can mix these typefaces in some ways: - -|| *Markup* || *Result* || -|| `_*bold* in italics_` || _*bold* in italics_ || -|| `*_italics_ in bold*` || *_italics_ in bold* || -|| `*~~strike~~ works too*` || *~~strike~~ works too* || -|| `~~as well as _this_ way round~~` || ~~as well as _this_ way round~~ || - -*IN HTML* - - -Tables: - -||* Name/Sample* || * Markup * || -|| _italic_ || `_italic_` || -|| *bold* || `*bold*` || -|| `code` || {{{`code`}}} || -|| {{{code}}} || `{{{code}}}` || -|| ^super^script || `^super^script` || -|| ,,sub,,script || `,,sub,,script` || -|| ~~strikeout~~ || `~~strikeout~~` || - -You can mix these typefaces in some ways: - -|| *Markup* || *Result* || -|| `_*bold* in italics_` || _*bold* in italics_ || -|| `*_italics_ in bold*` || *_italics_ in bold* || -|| `*~~strike~~ works too*` || *~~strike~~ works too* || -|| `~~as well as _this_ way round~~` || ~~as well as _this_ way round~~ || - - -==== Code (mismatched header sides again) ====== - -{{{ -{{{ -def fib(n): - if n == 0 or n == 1: - return n - else: - # This recursion is not good for large numbers. - return fib(n-1) + fib(n-2) -}}} -}}} - -Which results in: - -{{{ -def fib(n): - if n == 0 or n == 1: - return n - else: - # This recursion is not good for large numbers. - return fib(n-1) + fib(n-2) -}}} - -{{{ - - - -}}} - - - - - -*IN HTML* - - -{{{ -{{{ -def fib(n): - if n == 0 or n == 1: - return n - else: - # This recursion is not good for large numbers. - return fib(n-1) + fib(n-2) -}}} -}}} - -Which results in: - -{{{ -def fib(n): - if n == 0 or n == 1: - return n - else: - # This recursion is not good for large numbers. - return fib(n-1) + fib(n-2) -}}} - -{{{ - - - -}}} - - - - - - -==== Lists - -The following is: - * A list - * Of bulleted items - # This is a numbered sublist - # Which is done by indenting further - * And back to the main bulleted list - - * This is also a list - * With a single leading space - * Notice that it is rendered - # At the same levels - # As the above lists. - * Despite the different indentation levels. - - Blockquotes are seen as lists. Time to nest: - Nested! - Okay back. - -*IN HTML* - - -The following is: - * A list - * Of bulleted items - # This is a numbered sublist - # Which is done by indenting further - * And back to the main bulleted list - - * This is also a list - * With a single leading space - * Notice that it is rendered - # At the same levels - # As the above lists. - * Despite the different indentation levels. - - Blockquotes are seen as lists. Time to nest: - Nested! - Okay back. - - -==== Links - -A !LittleLink[TestPage ?] - -TestPage is linked automatically. - -http://www.google.com/ - -[http://www.google.com Google home page] - -[http://www.google.com https://www.google.com/images/srpr/logo11w.png] - -https://www.google.com/images/srpr/logo11w.png - -[https://www.google.com/images/srpr/logo11w.png An image] - -[https://www.google.com/images/srpr/logo11w.png https://www.google.com/images/srpr/logo11w.png] - -*IN HTML* - - -A !LittleLink[TestPage ?] - -TestPage is linked automatically. - -http://www.google.com/ - -[http://www.google.com Google home page] - -[http://www.google.com https://www.google.com/images/srpr/logo11w.png] - -https://www.google.com/images/srpr/logo11w.png - -[https://www.google.com/images/srpr/logo11w.png An image] - -[https://www.google.com/images/srpr/logo11w.png https://www.google.com/images/srpr/logo11w.png] - - -==== Issues - -This is issue 123, auto-linked. -This would be issue 456, but must link to old one. - -*IN HTML* - -This is issue 123, auto-linked. -This would be issue 456, but must link to old one. - -==== Revisions - -Revision 111605. - -rev111612. - -*IN HTML* - - -Revision 111605. - -rev111612. - - -==== Plugins - - -This text will be removed from the rendered page. - - - - - - - - -This text will be removed from the rendered page. - - - - - - - -==== Variables - -%%notdefined%% - -%%username%% - -%%email%% - -%%project%% - -*IN HTML* (with additional variable magic) - - -%%notdefined%% - -%%username%% - -%%email%% - -%%project%% - -%%myvar%% - - - -== All done!== - -Hope you enjoyed. - -= Regressions = - -We were adding extra spaces around tick marks: - -alpha `beta` gamma - diff --git a/wiki_to_md/impl/__init__.py b/wiki_to_md/impl/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/wiki_to_md/impl/constants.py b/wiki_to_md/impl/constants.py deleted file mode 100644 index 1a2e470..0000000 --- a/wiki_to_md/impl/constants.py +++ /dev/null @@ -1,187 +0,0 @@ -# Copyright 2014 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Constants used during conversion.""" -import re - - -# These are the various different matching possibilities Google Code -# recognizes. As matches are made, the respective handler class method is -# is called, which can do what it wishes with the match. - -# The pragmas: -PRAGMA_NAMES = ["summary", "labels", "sidebar"] -PRAGMA_RE = re.compile(r"^#(" + "|".join(PRAGMA_NAMES) + r")(.*)$") - -# Whitespace: -WHITESPACE_RE = re.compile(r"\s+") -INDENT_RE = re.compile(r"\A\s*") - -# Code blocks: -START_CODEBLOCK_RE = re.compile(r"^{{{$") -END_CODEBLOCK_RE = re.compile(r"^}}}$") - -# Line rules. These rules consume an entire line: -LINE_FORMAT_RULES = [ - r"""(?P - ^ - ----+ - $ - )""", - r"""(?P - ^ - =+\s* # Matches the leading delimiter - .* # Matches the heading title text - \s*=+\s* # Matches the trailing delimiter - $ - )""", -] -LINE_FORMAT_RE = re.compile("(?x)" + "|".join(LINE_FORMAT_RULES), re.UNICODE) - -# General formatting rules: -SIMPLE_FORMAT_RULE = r""" - (?P<{0}> - (?: - (?<=\W|_) # Match only if preceded by an authorized delimiter - {1} # The opening format character - ) | - (?: - {1} # Or match the closing format character... - (?=\W|_) # But only if followed by an authorized delimiter - ) | - - (?: - ^ # Or match the format character at the start of a line... - {1} - ) | - (?: - {1} # Or at the end of a line. - $ - ) - ) - """ - -URL_SCHEMA_RULE = r"(https?|ftp|nntp|news|mailto|telnet|file|irc)" -OPTIONAL_DESC_RULE = r"(?:\s+[^]]+)?" - -VALID_PAGENAME = r"(([A-Za-z0-9][A-Za-z0-9_]*)?[A-Za-z0-9])" - -# Link anchors use the Fragment ID pattern from RFC 1630. -# Dropping the quotes for security considerations. -XALPHA_RULE = r"[A-Za-z0-9%$-_@.&!*\(\),]" - -# Only WikiWords matching this pattern are detected and autolinked in the text. -WIKIWORD_AUTOLINK_RULE = ( - r"(?:[A-Z][a-z0-9]+_*)+(?:[A-Z][a-z0-9]+)(?:[#]{0}*?)?".format(XALPHA_RULE)) -WIKIWORD_RULE = r"(?:{0}?(?:[#]{1}*?)?)".format(VALID_PAGENAME, XALPHA_RULE) - -# "Plugins" are anything that looks like an XML/HTML tag. -PLUGIN_NAME = r"[a-zA-Z0-9_\-]+" # Matches a plugin name. -PLUGIN_ID = r"({0}:)?{0}".format(PLUGIN_NAME) # Matches a namespace and name. -PLUGIN_PARAM = r"""({0})\s*=\s*("[^"]*"|'[^']*'|\S+)""".format(PLUGIN_NAME) -PLUGIN = r"<{0}(?:\s+{1})*\s*/?>".format(PLUGIN_ID, PLUGIN_PARAM) -PLUGIN_END = r"".format(PLUGIN_ID) - -PLUGIN_ID_RE = re.compile(PLUGIN_ID, re.UNICODE) -PLUGIN_PARAM_RE = re.compile(PLUGIN_PARAM, re.UNICODE) -PLUGIN_RE = re.compile(PLUGIN, re.UNICODE) -PLUGIN_END_RE = re.compile(PLUGIN_END, re.UNICODE) - -TEXT_FORMAT_RULES = [ - SIMPLE_FORMAT_RULE.format("Bold", r"\*"), - SIMPLE_FORMAT_RULE.format("Italic", "_"), - SIMPLE_FORMAT_RULE.format("Strikethrough", "~~"), - r"\^(?P.+?)\^", - r",,(?P.+?),,", - r"`(?P.+?)`", - r"\{\{\{(?P.+?)\}\}\}", - r"""# Matches an entire table cell - (?P - (?:\|\|)+ # Any number of start markers, to support rowspan - .*? # Text of the table cell - (?=\|\|) # Assertion that we have a table cell end - )""", - r"(?P\|\|\s*$)", - r"""# Matches a freestanding URL in the source text. - (?P - \b(?:{0}://|(mailto:)) # Matches supported URL schemas - [^\s'\"<]+ # Match at least one character that is - # authorized within a URL. - [^\s'\"<.,}})\]]+ # After that, match all the way up to the first - # character that looks like a terminator. - )""".format(URL_SCHEMA_RULE), - r"""# Matches bracketed URLs: [http://foo.bar An optional description] - (?P - \[ - (?:{0}://|(mailto:)) # Matches supported URL schemas - [^]\s]+ # Matches up to the closing bracket or whitespace - {1} # Matches the optional URL description - \] - )""".format(URL_SCHEMA_RULE, OPTIONAL_DESC_RULE), - r"""# Matches a WikiWord embedded in the text. - (?: - (? - !? # The WikiWord is preceded by an optional exclamation - # mark, which makes it not a link. However, we still - # need to match it as being a link, so that we can strip - # the exclamation mark from the resulting plaintext WikiWord. - - {0} # The WikiWord itself - ) - - (?![A-Za-z0-9]) # Matches the WikiWord only if it's not followed - # by alphanumeric characters. - )""".format(WIKIWORD_AUTOLINK_RULE), - r"""# Matches a forced/named WikiLink: [WikiWord an optional description] - (?P - \[ - {0} # Matches the WikiWord - {1} # Matches the optional WikiLink description - \] - )""".format(WIKIWORD_RULE, OPTIONAL_DESC_RULE), - r"""# Matches an issue reference. - (?P - ( - \b([Ii][Ss][Ss][Uu][Ee]|[Bb][Uu][Gg])\s*\#? - ) - \d+\b - ) - """, - r"""# Matches a revision reference. - (?P - ( - \b[Rr]([Ee][Vv][Ii][Ss][Ii][Oo][Nn]\s*\#?)? - ) - \d+\b - ) - """, - r"(?P{0})".format(PLUGIN), - r"(?P{0})".format(PLUGIN_END), - r"""# Matches a variable being used, defined in a plugin or globally. - %%(?P[\w|_|\-]+)%%""" -] -TEXT_FORMAT_RE = re.compile("(?x)" + "|".join(TEXT_FORMAT_RULES), re.UNICODE) - -# For verification of YouTube video IDs. -YOUTUBE_VIDEO_ID_RE = re.compile("^[a-zA-Z0-9_-]+$") - -# List types: -LIST_TYPES = { - "1": "numeric", - "#": "numeric", - "*": "bullet", - " ": "blockquote", -} diff --git a/wiki_to_md/impl/converter.py b/wiki_to_md/impl/converter.py deleted file mode 100644 index f1128d5..0000000 --- a/wiki_to_md/impl/converter.py +++ /dev/null @@ -1,1281 +0,0 @@ -# Copyright 2014 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Handles conversion of Wiki files.""" -import urlparse - -from . import constants - - -class Converter(object): - """Class that handles the actual parsing and generation.""" - - # A map of HTML tags to a list of the supported args for that tag. - _BASIC_HTML_ARGS = ["title", "dir", "lang"] - _BASIC_HTML_SIZEABLE_ARGS = (_BASIC_HTML_ARGS + - ["border", "height", "width", "align"]) - _BASIC_HTML_TABLE_ARGS = (_BASIC_HTML_SIZEABLE_ARGS + - ["valign", "cellspacing", "cellpadding"]) - _ALLOWED_HTML_TAGS = { - "a": _BASIC_HTML_ARGS + ["href"], - "b": _BASIC_HTML_ARGS, - "br": _BASIC_HTML_ARGS, - "blockquote": _BASIC_HTML_ARGS, - "code": _BASIC_HTML_ARGS + ["language"], - "dd": _BASIC_HTML_ARGS, - "div": _BASIC_HTML_ARGS, - "dl": _BASIC_HTML_ARGS, - "dt": _BASIC_HTML_ARGS, - "em": _BASIC_HTML_ARGS, - "font": _BASIC_HTML_ARGS + ["face", "size", "color"], - "h1": _BASIC_HTML_ARGS, - "h2": _BASIC_HTML_ARGS, - "h3": _BASIC_HTML_ARGS, - "h4": _BASIC_HTML_ARGS, - "h5": _BASIC_HTML_ARGS, - "i": _BASIC_HTML_ARGS, - "img": _BASIC_HTML_SIZEABLE_ARGS + ["src", "alt"], - "li": _BASIC_HTML_ARGS, - "ol": _BASIC_HTML_ARGS + ["type", "start"], - "p": _BASIC_HTML_ARGS + ["align"], - "pre": _BASIC_HTML_ARGS, - "q": _BASIC_HTML_ARGS, - "s": _BASIC_HTML_ARGS, - "span": _BASIC_HTML_ARGS, - "strike": _BASIC_HTML_ARGS, - "strong": _BASIC_HTML_ARGS, - "sub": _BASIC_HTML_ARGS, - "sup": _BASIC_HTML_ARGS, - "table": _BASIC_HTML_TABLE_ARGS, - "tbody": _BASIC_HTML_TABLE_ARGS, - "td": _BASIC_HTML_TABLE_ARGS, - "tfoot": _BASIC_HTML_TABLE_ARGS, - "th": _BASIC_HTML_TABLE_ARGS, - "thead": _BASIC_HTML_TABLE_ARGS + ["colspan", "rowspan"], - "tr": _BASIC_HTML_TABLE_ARGS + ["colspan", "rowspan"], - "tt": _BASIC_HTML_ARGS, - "u": _BASIC_HTML_ARGS, - "ul": _BASIC_HTML_ARGS + ["type"], - "var": _BASIC_HTML_ARGS, - } - - # These plugins consume raw text. - _RAW_PLUGINS = ["code", "wiki:comment", "pre"] - - # Parameters supported by the g:plusone plugin. - _PLUSONE_ARGS = ["count", "size", "href"] - - # Parameters supported by the wiki:video plugin. - _VIDEO_ARGS = ["url", "width", "height"] - _VIDEO_DEFAULT_WIDTH = "425" - _VIDEO_DEFAULT_HEIGHT = "344" - - def __init__( - self, - pragma_handler, - formatting_handler, - warning_method, - project, - wikipages): - """Create a converter. - - Args: - pragma_handler: Handler for parsed pragmas. - formatting_handler: Handler for parsed formatting rules. - warning_method: A function to call to display a warning message. - project: The name of the Google Code project for the Wiki page. - wikipages: Wiki pages assumed to exist for auto-linking. - """ - self._pragma_handler = pragma_handler - self._formatting_handler = formatting_handler - self._warning_method = warning_method - self._wikipages = wikipages - self._project = project - - def Convert(self, input_stream, output_stream): - """Converts a file in Google Code Wiki format to Github-flavored Markdown. - - Args: - input_stream: Input Wiki file. - output_stream: Output Markdown file. - """ - # For simpler processing just load the entire file into memory. - input_lines = input_stream.readlines() - input_line = 1 - - # First extract pragmas, which must be placed at the top of the file. - input_line = self._ExtractPragmas(input_line, input_lines, output_stream) - - # Now ignore any starting vertical whitespace. - input_line = self._MoveToMain(input_line, input_lines, output_stream) - - # At the main text, begin processing. - input_line = self._ProcessBody(input_line, input_lines, output_stream) - - # Done, but sanity check the amount of input processed. - remaining_lines = len(input_lines) - input_line + 1 - if remaining_lines != 0: - self._warning_method( - input_line, - u"Processing completed, but not all lines were processed. " - "Remaining lines: {0}.".format(remaining_lines)) - - def _ExtractPragmas(self, input_line, input_lines, output_stream): - """Extracts pragmas from a given input. - - Args: - input_line: Current line number being processed. - input_lines: Input Wiki file lines. - output_stream: Output Markdown file. - Returns: - The new value of input_line after processing. - """ - for line in input_lines[input_line - 1:]: - pragma_match = constants.PRAGMA_RE.match(line) - if not pragma_match: - # Found all the pragmas. - break - - # Found a pragma, strip it and pass it to the handler. - pragma_type, pragma_value = pragma_match.groups() - - self._pragma_handler.HandlePragma( - input_line, - output_stream, - pragma_type.strip(), - pragma_value.strip()) - - # Moving on to the next line. - input_line += 1 - - return input_line - - def _MoveToMain(self, input_line, input_lines, unused_output_stream): - """Move the input line position to the main body, after pragmas. - - Args: - input_line: Current line number being processed. - input_lines: Input Wiki file lines. - Returns: - The new value of input_line after processing. - """ - for line in input_lines[input_line - 1:]: - whitespace_match = constants.WHITESPACE_RE.match(line) - if not whitespace_match: - # Skipped all the whitespace. - break - - # Moving on to the next line. - input_line += 1 - - return input_line - - def _ProcessBody(self, input_line, input_lines, output_stream): - """The process core. - - It is a simple loop that tries to match formatting rules - then pass it to the correct handler. It processes the matches - in the same order as Google Code's wiki parser. - - Args: - input_line: Current line number being processed. - input_lines: Input Wiki file lines. - output_stream: Output Markdown file. - Returns: - The new value of input_line after processing. - """ - # State tracked during processing: - self._code_block_depth = 0 # How many code block openings we've seen. - self._code_block_lines = [] # What lines we've collected for a code block. - self._indents = [] # 2-tuple of indent position and list type. - self._open_tags = [] # List of open tags, like bold or italic. - self._table_columns = [] # Table column sizes, taken from the header row. - self._table_column = 0 # Current column in the table body, or zero if none. - self._plugin_stack = [] # Current stack of plugins and their parameters. - - first_line = True - for line in input_lines[input_line - 1:]: - stripped_line = line.strip() - - self._ProcessLine( - first_line, - input_line, - line, - stripped_line, - output_stream) - - # Moving on to the next line. - input_line += 1 - first_line = False - - if self._code_block_depth: - # Forgotten code block ending, close it implicitly. - code = "".join(self._code_block_lines) - self._formatting_handler.HandleText(input_line, output_stream, code) - self._formatting_handler.HandleCodeBlockClose(input_line, output_stream) - - return input_line - - def _ProcessLine( - self, - first_line, - input_line, - line, - stripped_line, - output_stream): - """Processes a single line, depending on state. - - Args: - first_line: True if this is the first line, false otherwise. - input_line: Current line number being processed. - line: The raw line string. - stripped_line: The line string, stripped of surrounding whitepsace. - output_stream: Output Markdown file. - Returns: - The new value of input_line after processing. - """ - # Check for the start of a code block. - if constants.START_CODEBLOCK_RE.match(stripped_line): - if self._code_block_depth == 0: - # Start a new collection of lines. - self._code_block_lines = [] - else: - # Just an embedded code block. - self._code_block_lines.append(line) - self._code_block_depth += 1 - return - - # Check for the end of a code block. - if constants.END_CODEBLOCK_RE.match(stripped_line): - self._code_block_depth -= 1 - if self._code_block_depth == 0: - # Closed the highest-level code block, handle it. - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - "\n") - self._formatting_handler.HandleCodeBlockOpen( - input_line, - output_stream, - None) - code = "".join(self._code_block_lines) - self._formatting_handler.HandleText(input_line, output_stream, code) - self._formatting_handler.HandleCodeBlockClose(input_line, output_stream) - else: - # Just closed an embedded clode block. - self._code_block_lines.append(line) - return - - # Check if we're in a code block. - # If we are, just put the raw text into code_block_lines. - if self._code_block_depth != 0: - self._code_block_lines.append(line) - return - - # For empty lines, close all formatting. - if not stripped_line: - if not self._ConsumeTextForPlugin(): - self._SetCurrentList(input_line, 0, " ", output_stream) - self._CloseTags(input_line, output_stream) - - if self._table_columns: - self._formatting_handler.HandleTableClose(input_line, output_stream) - self._table_columns = [] - self._table_column = 0 - - self._formatting_handler.HandleParagraphBreak(input_line, output_stream) - return - - # Non-empty line, finish the previous line's newline. - if not first_line: - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - "\n") - - # Now check if we're processing within a list. - indent_pos = constants.INDENT_RE.match(line).end() - if (indent_pos and indent_pos < len(line) and - not self._ConsumeTextForPlugin()): - list_type = constants.LIST_TYPES.get(line[indent_pos], "blockquote") - - if self._SetCurrentList(input_line, indent_pos, list_type, output_stream): - # Blockquotes take the entire remainder of the line, - # but everything else skips the list symbol plus the space after. - # (In case there is no space after, the first character is skipped; - # we will warn if this is detected, as it was probably unintended.) - if list_type == "blockquote": - line = line[indent_pos:] - else: - if line[indent_pos + 1] != " ": - self._warning_method( - input_line, - u"Missing space after list symbol: {0}, " - "'{1}' was removed instead." - .format(line[indent_pos], line[indent_pos + 1])) - line = line[indent_pos + 2:] - - stripped_line = line.strip() - else: - # Reset to no indent. - self._SetCurrentList(input_line, 0, " ", output_stream) - - # Finally, split the line into formatting primitives. - # We do so without whitespace so we can catch line breaks across tags. - if constants.LINE_FORMAT_RE.match(stripped_line): - self._ProcessMatch( - input_line, - constants.LINE_FORMAT_RE, - stripped_line, - output_stream) - else: - self._ProcessMatch( - input_line, - constants.TEXT_FORMAT_RE, - stripped_line, - output_stream) - - self._CloseTableRow(input_line, output_stream) - - def _SetCurrentList(self, input_line, indent_pos, list_type, output_stream): - """Set the current list level based on the indentation. - - Args: - input_line: Current line number being processed. - indent_pos: How far into the line we are indented. - list_type: What the type of the list should be. - output_stream: Output Markdown file. - Returns: - True if we are in a list item, False otherwise. - """ - # Pop and close the lists until we hit a - # list that is at the current position and type - while self._indents and self._indents[-1][0] >= indent_pos: - indents_top = self._indents[-1] - if indents_top[0] == indent_pos and indents_top[1] == list_type: - break - - self._formatting_handler.HandleListClose(input_line, output_stream) - self._indents.pop() - - # If we just popped everything off, we're not in a list. - if indent_pos == 0: - return False - - if not self._indents or indent_pos >= self._indents[-1][0]: - # Add a new indentation if this is the first item overall, - # or the first item at this indentation position. - if not self._indents or indent_pos > self._indents[-1][0]: - self._indents.append((indent_pos, list_type)) - - # Add the leading Markdown for the list. - indentation_level = len(self._indents) - if list_type == "numeric": - self._formatting_handler.HandleNumericListOpen( - input_line, - output_stream, - indentation_level) - elif list_type == "bullet": - self._formatting_handler.HandleBulletListOpen( - input_line, - output_stream, - indentation_level) - elif list_type == "blockquote": - self._formatting_handler.HandleBlockQuoteOpen( - input_line, - output_stream, - indentation_level) - else: - self._warning_method( - input_line, - u"Bad list type: '{0}'".format(list_type)) - - return True - - def _OpenTag(self, input_line, tag, output_stream): - """Open a tag and add it to the open tags list. - - Args: - input_line: Current line number being processed. - tag: Tag to open. - output_stream: Output Markdown file. - """ - handler = getattr( - self._formatting_handler, u"Handle{0}Open".format(tag), None) - if handler: - handler(input_line, output_stream) - else: - self._warning_method(input_line, u"Bad open tag: '{0}'".format(tag)) - - self._open_tags.append(tag) - - def _CloseTag(self, input_line, tag, output_stream): - """Close a tag and remove it from the open tags list. - - Args: - input_line: Current line number being processed. - tag: Tag to close. - output_stream: Output Markdown file. - """ - handler = getattr( - self._formatting_handler, u"Handle{0}Close".format(tag), None) - if handler: - handler(input_line, output_stream) - else: - self._warning_method(input_line, u"Bad close tag: '{0}'".format(tag)) - - self._open_tags.remove(tag) - - def _CloseTags(self, input_line, output_stream): - """Close all tags. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - for tag in self._open_tags: - self._CloseTag(input_line, tag, output_stream) - - def _CloseTableRow(self, input_line, output_stream): - """Close table row, if any. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - if self._table_columns: - if self._table_column != 1: - self._formatting_handler.HandleTableRowEnd(input_line, output_stream) - - # Check if we just finished the header row. - if not self._table_column: - self._formatting_handler.HandleTableHeader( - input_line, - output_stream, - self._table_columns) - - # In a table body, set the current column to 1. - self._table_column = 1 - - def _ConsumeTextForPlugin(self): - """Check if text should be consumed raw for a plugin. - - Returns: - True if the current plugin is consuming raw text, false otherwise. - """ - return (self._plugin_stack and - self._plugin_stack[-1]["id"] in self._RAW_PLUGINS) - - def _ProcessMatch(self, input_line, match_regex, line, output_stream): - """Process text, using a regex to match against. - - Args: - input_line: Current line number being processed. - match_regex: Regex to match the line against. - line: The line being processed. - output_stream: Output Markdown file. - """ - lastpos = 0 - for fullmatch in match_regex.finditer(line): - # Add text before the match as regular text. - if lastpos < fullmatch.start(): - starting_line = line[lastpos:fullmatch.start()] - if self._ConsumeTextForPlugin(): - self._formatting_handler.HandleText( - input_line, - output_stream, - starting_line) - else: - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - starting_line) - - for rulename, match in fullmatch.groupdict().items(): - if match is not None: - if self._ConsumeTextForPlugin() and rulename != "PluginEnd": - self._formatting_handler.HandleText( - input_line, - output_stream, - match) - else: - handler = getattr(self, u"_Handle{0}".format(rulename), None) - handler(input_line, match, output_stream) - - lastpos = fullmatch.end() - - # Add remainder of the line as regular text. - if lastpos < len(line): - remaining_line = line[lastpos:] - if self._ConsumeTextForPlugin(): - self._formatting_handler.HandleText( - input_line, - output_stream, - remaining_line) - else: - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - remaining_line) - - def _HandleHeading(self, input_line, match, output_stream): - """Handle a heading formatter. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - match = match.strip() - - # Count the equals on the left side. - leftequalcount = 0 - for char in match: - if char != "=": - break - leftequalcount += 1 - - # Count the equals on the right side. - rightequalcount = 0 - for char in reversed(match): - if char != "=": - break - rightequalcount += 1 - - # Users often forget to have the same number of equals signs on - # both sides. Rather than simply error out, we say the level is - # the number of equals signs on the left side. - header_level = leftequalcount - - # If the level is greater than 6, the header is invalid and the contents - # are parsed as if no header markup were provided. - if header_level > 6: - header_level = None - - # Everything else is the heading text. - heading_text = match[leftequalcount:-rightequalcount].strip() - - if header_level: - self._formatting_handler.HandleHeaderOpen( - input_line, - output_stream, - header_level) - - self._ProcessMatch( - input_line, - constants.TEXT_FORMAT_RE, - heading_text, - output_stream) - - if header_level: - self._formatting_handler.HandleHeaderClose( - input_line, - output_stream, - header_level) - - def _HandleHRule(self, input_line, unused_match, output_stream): - """Handle a heading formatter. - - Args: - input_line: Current line number being processed. - unused_match: Matched text. - output_stream: Output Markdown file. - """ - self._formatting_handler.HandleHRule(input_line, output_stream) - - def _HandleBold(self, input_line, unused_match, output_stream): - """Handle a bold formatter. - - Args: - input_line: Current line number being processed. - unused_match: Matched text. - output_stream: Output Markdown file. - """ - self._HandleTag(input_line, "Bold", output_stream) - - def _HandleItalic(self, input_line, unused_match, output_stream): - """Handle a italic formatter. - - Args: - input_line: Current line number being processed. - unused_match: Matched text. - output_stream: Output Markdown file. - """ - self._HandleTag(input_line, "Italic", output_stream) - - def _HandleStrikethrough(self, input_line, unused_match, output_stream): - """Handle a strikethrough formatter. - - Args: - input_line: Current line number being processed. - unused_match: Matched text. - output_stream: Output Markdown file. - """ - self._HandleTag(input_line, "Strikethrough", output_stream) - - def _HandleSuperscript(self, input_line, match, output_stream): - """Handle superscript. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - self._formatting_handler.HandleSuperscript(input_line, output_stream, match) - - def _HandleSubscript(self, input_line, match, output_stream): - """Handle subscript. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - self._formatting_handler.HandleSubscript(input_line, output_stream, match) - - def _HandleInlineCode(self, input_line, match, output_stream): - """Handle inline code, method one. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - self._formatting_handler.HandleInlineCode(input_line, output_stream, match) - - def _HandleInlineCode2(self, input_line, match, output_stream): - """Handle inline code, method two. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - self._formatting_handler.HandleInlineCode(input_line, output_stream, match) - - def _HandleTableCell(self, input_line, match, output_stream): - """Handle a table cell. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - # Table cells end previous formatting. - self._CloseTags(input_line, output_stream) - - # Count the pipes to calculate the column span. - pipecount = 0 - for char in match: - if char != "|": - break - pipecount += 1 - - span = pipecount / 2 - - # Now output the cell, tracking the size of the contents. - self._formatting_handler.HandleTableCellBorder(input_line, output_stream) - - starting_pos = output_stream.tell() - self._ProcessMatch( - input_line, - constants.TEXT_FORMAT_RE, - match[pipecount:], - output_stream) - ending_pos = output_stream.tell() - - # Handle the cell width, either tracking or padding. - cell_width = ending_pos - starting_pos - if not self._table_column: - # In the header row, track the column sizes. - self._table_columns.append(cell_width) - else: - # In the table body, pad the cell (for prettier raw text viewing). - header_cell_width = self._table_columns[self._table_column - 1] - remaining_width = header_cell_width - cell_width - if remaining_width > 0: - padding = " " * remaining_width - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - padding) - - self._table_column += 1 - - if span > 1: - self._warning_method( - input_line, - "Multi-span cells are not directly supported in GFM. They have been " - "emulated by adding empty cells. This may give the correct rendered " - "result, but the plain-text representation may be noisy. Consider " - "removing the multi-span cells from your table, or using HTML.") - while span > 1: - # Empty cell. - self._formatting_handler.HandleTableCellBorder( - input_line, - output_stream) - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - " ") - self._table_columns.append(1) - - span -= 1 - - def _HandleTableRowEnd(self, input_line, unused_match, output_stream): - """Handle a table row ending. - - Args: - input_line: Current line number being processed. - unused_match: Matched text. - output_stream: Output Markdown file. - """ - # Table cells end previous formatting. - self._CloseTags(input_line, output_stream) - - self._CloseTableRow(input_line, output_stream) - - def _HandleUrl(self, input_line, match, output_stream): - """Handle an auto-linked URL. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - self._formatting_handler.HandleLink(input_line, output_stream, match, None) - - def _HandleUrlBracket(self, input_line, match, output_stream): - """Handle a bracketed URL. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - # First, strip the brackets off to get to the URL and description. - core = match[1:-1] - - # Now strip out the description. - parts = constants.WHITESPACE_RE.split(core, 1) - if len(parts) == 1: - url = parts[0] - description = None - else: - url = parts[0] - description = parts[1] - - self._formatting_handler.HandleLink( - input_line, - output_stream, - url, - description) - - def _HandleWikiWord(self, input_line, match, output_stream): - """Handle a wiki word. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - if match[0] == "!": - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - match[1:]) - elif match not in self._wikipages: - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - match) - else: - self._formatting_handler.HandleWiki( - input_line, - output_stream, - match, - None) - - def _HandleWikiWordBracket(self, input_line, match, output_stream): - """Handle a bracketed wiki word. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - # First, strip the brackets off to get to the wiki and description. - core = match[1:-1] - - # Now strip out the description. - parts = constants.WHITESPACE_RE.split(core, 1) - if len(parts) == 1: - wiki = parts[0] - description = None - else: - wiki = parts[0] - description = parts[1] - - self._formatting_handler.HandleWiki( - input_line, - output_stream, - wiki, - description) - - def _HandleIssueLink(self, input_line, match, output_stream): - """Handle an auto-linked issue. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - issue = match[len("issue"):].strip() - prefix = match[:-len(issue)] - - self._formatting_handler.HandleIssue( - input_line, - output_stream, - prefix, - issue) - - def _HandleRevisionLink(self, input_line, match, output_stream): - """Handle an auto-linked revision. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - if match[1].lower() == "e": - revision = match[len("revision"):].strip() - else: - revision = match[len("r"):].strip() - prefix = match[:-len(revision)] - - self._formatting_handler.HandleRevision( - input_line, - output_stream, - prefix, - revision) - - def _HandlePlugin(self, input_line, match, output_stream): - """Handle a plugin tag. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - # Plugins close formatting tags. - self._CloseTags(input_line, output_stream) - - # Get the core of the tag, check if this is also an end tag. - if match.endswith("/>"): - core = match[1:-2] - has_end = True - else: - core = match[1:-1] - has_end = False - - # Extract the ID for the plugin. - plugin_id = constants.PLUGIN_ID_RE.match(core).group(0) - core_params = core[len(plugin_id):].strip() - - # Extract the parameters for the plugin. - params = {} - for name, value in constants.PLUGIN_PARAM_RE.findall(core_params): - # Remove quotes from the value, if they exist - if value.startswith("'"): - value = value.strip("'") - elif value.startswith("\""): - value = value.strip("\"") - params[name] = value - - # Now figure out what to do with the plugin. - if plugin_id in self._ALLOWED_HTML_TAGS: - self._HandlePluginHtml( - input_line, - plugin_id, - params, - has_end, - output_stream) - elif plugin_id == "g:plusone": - self._HandlePluginGPlus( - input_line, - plugin_id, - params, - output_stream) - elif plugin_id == "wiki:comment": - self._HandlePluginWikiComment( - input_line, - plugin_id, - params, - output_stream) - elif plugin_id == "wiki:gadget": - self._HandlePluginWikiGadget(input_line, match, output_stream) - elif plugin_id == "wiki:video": - self._HandlePluginWikiVideo( - input_line, - plugin_id, - params, - output_stream) - elif plugin_id == "wiki:toc": - self._HandlePluginWikiToc(input_line, match, output_stream) - else: - self._warning_method( - input_line, - u"Unknown plugin was given, outputting " - "as plain text:\n\t{0}".format(match)) - # Wiki syntax put this class of error on its own line. - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - u"\n\n{0}\n\n".format(match)) - - # Add plugin and parameters to the stack. - if not has_end: - plugin_info = {"id": plugin_id, "params": params} - self._plugin_stack.append(plugin_info) - - def _HandlePluginHtml( - self, - input_line, - plugin_id, - params, - has_end, - output_stream): - """Handle a plugin tag for HTML. - - Args: - input_line: Current line number being processed. - plugin_id: The plugin ID. - params: The plugin params. - has_end: Plugin has an end tag. - output_stream: Output Markdown file. - """ - # Filter the parameters. These are only filtered for output, - # they still have the effect of being usable variables. - allowed_parameters = self._ALLOWED_HTML_TAGS[plugin_id] - filtered_params = {} - for name, value in params.items(): - if name in allowed_parameters: - filtered_params[name] = value - else: - self._warning_method( - input_line, - u"The following parameter was given for the '{0}' tag, " - "but will not be present in the outputted HTML:\n\t'{1}': '{2}'" - .format(plugin_id, name, value)) - - if plugin_id == "code": - self._formatting_handler.HandleCodeBlockOpen( - input_line, - output_stream, - filtered_params.get("language")) - else: - self._formatting_handler.HandleHtmlOpen( - input_line, - output_stream, - plugin_id, - filtered_params, - has_end) - - def _HandlePluginGPlus( - self, - input_line, - plugin_id, - params, - output_stream): - """Handle a plugin tag for +1 button. - - Args: - input_line: Current line number being processed. - plugin_id: The plugin ID. - params: The plugin params. - output_stream: Output Markdown file. - """ - filtered_params = {} - for name, value in params.items(): - if name in self._PLUSONE_ARGS: - filtered_params[name] = value - else: - self._warning_method( - input_line, - u"The following parameter was given for the '{0}' tag, " - "but will not be present in the outputted HTML:\n\t'{1}': '{2}'" - .format(plugin_id, name, value)) - - self._formatting_handler.HandleGPlusOpen( - input_line, - output_stream, - filtered_params) - - def _HandlePluginWikiComment( - self, - input_line, - plugin_id, - params, - output_stream): - """Handle a plugin tag for a wiki comment. - - Args: - input_line: Current line number being processed. - plugin_id: The plugin ID. - params: The plugin params. - output_stream: Output Markdown file. - """ - for name, value in params.items(): - self._warning_method( - input_line, - u"The following parameter was given for the '{0}' tag, " - "but will not be present in the outputted HTML:\n\t'{1}': '{2}'" - .format(plugin_id, name, value)) - - self._formatting_handler.HandleCommentOpen(input_line, output_stream) - - def _HandlePluginWikiGadget(self, input_line, match, output_stream): - """Handle a plugin tag for a wiki gadget. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - self._warning_method( - input_line, - u"A wiki gadget was used, but this must be manually converted to a " - "GFM-supported method, if possible. Outputting as plain text:\n\t{0}" - .format(match)) - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - match) - - def _HandlePluginWikiVideo( - self, - input_line, - plugin_id, - params, - output_stream): - """Handle a plugin tag for a wiki video. - - Args: - input_line: Current line number being processed. - plugin_id: The plugin ID. - params: The plugin params. - output_stream: Output Markdown file. - """ - filtered_params = {} - for name, value in params.items(): - if name in self._VIDEO_ARGS: - filtered_params[name] = value - else: - self._warning_method( - input_line, - u"The following parameter was given for the '{0}' tag, " - "but will not be present in the outputted HTML:\n\t'{1}': '{2}'" - .format(plugin_id, name, value)) - - if "url" in filtered_params: - width = filtered_params.get("width", self._VIDEO_DEFAULT_WIDTH) - height = filtered_params.get("height", self._VIDEO_DEFAULT_HEIGHT) - extracted = urlparse.urlparse(filtered_params["url"]) - query = urlparse.parse_qs(extracted.query) - video_id = query.get("v", [""])[0] - if not video_id and extracted.path.startswith("/v/"): - video_id = extracted.path[3:] - if not constants.YOUTUBE_VIDEO_ID_RE.match(video_id): - output = ("wiki:video: cannot find YouTube " - "video id within parameter \"url\".") - self._warning_method( - input_line, - u"Video plugin has invalid video ID, outputting error:\n\t{0}" - .format(output)) - # Wiki syntax put this class of error on its own line. - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - u"\n\n{0}\n\n".format(output)) - else: - self._formatting_handler.HandleVideoOpen( - input_line, - output_stream, - video_id, - width, - height) - else: - output = "wiki:video: missing mandatory parameter \"url\"." - self._warning_method( - input_line, - u"Video plugin is missing 'url' parameter, outputting error:\n\t{0}" - .format(output)) - # Wiki syntax put this class of error on its own line. - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - u"\n\n{0}\n\n".format(output)) - - def _HandlePluginWikiToc(self, input_line, match, output_stream): - """Handle a plugin tag for a wiki table of contents. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - self._warning_method( - input_line, - u"A table of contents plugin was used for this wiki:\n" - "\t{0}\n" - "The Gollum wiki system supports table of content generation.\n" - "See https://github.com/gollum/gollum/wiki for more information.\n" - "It has been removed." - .format(match)) - - def _HandlePluginEnd(self, input_line, match, output_stream): - """Handle a plugin ending tag. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - core = match[2:-1] - plugin_id = constants.PLUGIN_ID_RE.match(core).group(0) - - if self._plugin_stack and self._plugin_stack[-1]["id"] == plugin_id: - self._plugin_stack.pop() - - if plugin_id in self._ALLOWED_HTML_TAGS: - if plugin_id == "code": - self._formatting_handler.HandleCodeBlockClose( - input_line, - output_stream) - else: - self._formatting_handler.HandleHtmlClose( - input_line, - output_stream, - plugin_id) - elif plugin_id == "g:plusone": - self._formatting_handler.HandleGPlusClose(input_line, output_stream) - elif plugin_id == "wiki:comment": - self._formatting_handler.HandleCommentClose(input_line, output_stream) - elif plugin_id == "wiki:gadget": - # A warning was already issued on the opening tag. - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - match) - elif plugin_id == "wiki:video": - self._formatting_handler.HandleVideoClose(input_line, output_stream) - elif plugin_id == "wiki:toc": - # A warning was already issued on the opening tag. - pass - else: - self._warning_method( - input_line, - u"Unknown but matching plugin end was given, outputting " - "as plain text:\n\t{0}".format(match)) - # Wiki syntax put this class of error on its own line. - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - u"\n\n{0}\n\n".format(match)) - else: - self._warning_method( - input_line, - u"Unknown/unmatched plugin end was given, outputting " - "as plain text with errors:\n\t{0}".format(match)) - # Wiki syntax put this class of error on its own line, - # with a prefix error message, and did not display the tag namespace. - tag_without_ns = plugin_id.split(":", 1)[-1] - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - u"\n\nUnknown end tag for \n\n".format(tag_without_ns)) - - def _HandleVariable(self, input_line, match, output_stream): - """Handle a variable. - - Args: - input_line: Current line number being processed. - match: Matched text. - output_stream: Output Markdown file. - """ - output = None - instructions = None - - # If the variable is defined somewhere in the plugin stack, use it. - if self._plugin_stack: - value = None - for plugin_info in reversed(self._plugin_stack): - if match in plugin_info["params"]: - value = plugin_info["params"][match] - break - - if value: - output = value - - # Otherwise, it needs to be globally-defined. - if not output and match == "username": - output = "(TODO: Replace with username.)" - instructions = ("On Google Code this would have been replaced with the " - "username of the current user, but GitHub has no " - "direct support for equivalent behavior. It has been " - "replaced with\n\t{0}\nConsider removing this altogether." - .format(output)) - elif not output and match == "email": - output = "(TODO: Replace with email address.)" - instructions = ("On Google Code this would have been replaced with the " - "email address of the current user, but GitHub has no " - "direct support for equivalent behavior. It has been " - "replaced with\n\t{0}\nConsider removing this altogether." - .format(output)) - elif not output and match == "project": - if self._project: - output = self._project - instructions = (u"It has been replaced with static text containing the " - "name of the project:\n\t{0}".format(self._project)) - else: - output = "(TODO: Replace with project name.)" - instructions = ("Because no project name was specified, the text has " - "been replaced with:\n\t{0}".format(output)) - - # Not defined anywhere, just treat as regular text. - if not output: - # Add surrounding %% back on. - output = u"%%{0}%%".format(match) - - self._formatting_handler.HandleEscapedText( - input_line, - output_stream, - output) - if instructions: - self._warning_method( - input_line, - u"A variable substitution was performed with %%{0}%%. {1}" - .format(match, instructions)) - - def _HandleTag(self, input_line, tag, output_stream): - """Handle a tag, which has an opening and closing. - - Args: - input_line: Current line number being processed. - tag: The tag to handle. - output_stream: Output Markdown file. - """ - if tag not in self._open_tags: - self._OpenTag(input_line, tag, output_stream) - else: - self._CloseTag(input_line, tag, output_stream) diff --git a/wiki_to_md/impl/formatting_handler.py b/wiki_to_md/impl/formatting_handler.py deleted file mode 100644 index 664fc26..0000000 --- a/wiki_to_md/impl/formatting_handler.py +++ /dev/null @@ -1,1044 +0,0 @@ -# Copyright 2014 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Handles converting of formatting.""" -import cgi - -from . import constants - - -class FormattingHandler(object): - """Class that handles the conversion of formatting.""" - - # Links with these URL schemas are auto-linked by GFM. - _GFM_AUTO_URL_SCHEMAS = ("http://", "https://") - - # Images that were inlined automatically by Wiki syntax - # had to have these URL schemas and image extensions. - _IMAGE_URL_SCHEMAS = ("http://", "https://", "ftp://") - _IMAGE_EXTENSIONS = (".png", ".gif", ".jpg", ".jpeg", ".svg") - - # Template for linking to a video. - _VIDEO_TEMPLATE = ( - u"") - - # Formatting tags for list-to-HTML conversion. - _HTML_LIST_TAGS = { - "Numeric list": { - "ListTag": "ol", - "ItemTag": "li", - }, - "Bulleted list": { - "ListTag": "ul", - "ItemTag": "li", - }, - "Blockquote": { - "ListTag": "blockquote", - "ItemTag": None, - }, - } - - # Formatting tags for formatting-to-HTML conversion. - _HTML_FORMAT_TAGS = { - "Bold": { - "Markdown": "**", - "HTML": "b", - }, - "Italic": { - "Markdown": "_", - "HTML": "i", - }, - "Strikethrough": { - "Markdown": "~~", - "HTML": "del", - }, - } - - # How a single indentation is outputted. - _SINGLE_INDENTATION = " " * 2 - - def __init__(self, warning_method, project, issue_map, symmetric_headers): - """Create a formatting handler. - - Args: - warning_method: A function to call to display a warning message. - project: The name of the Google Code project for the Wiki page. - issue_map: A dictionary of Google Code issues to GitHub issues. - symmetric_headers: True if header denotations are symmetric. - """ - self._warning_method = warning_method - self._project = project - self._issue_map = issue_map - self._symmetric_headers = symmetric_headers - - # GFM has a quirk with nested blockquotes where a blank line is needed - # after closing a nested blockquote while continuing into another. - self._last_blockquote_indent = 0 - - # GFM will not apply formatting if whitespace surrounds the text being - # formatted, but Wiki will. To work around this, we maintain a buffer - # of text to be outputted, and when the tag is closed we can trim the - # buffer before applying formatting. If the trimmed buffer is empty, we - # can omit the formatting altogether to avoid GFM rendering issues. - self._format_buffer = [] - - # GitHub won't render formatting within HTML tags. Track if this is the - # case so we can issue a warning and try a work-around. - self._in_html = 0 # Number of tags currently open. - self._in_code_block = False # If we're in a code block in HTML. - self._has_written_text = False # If we've written text since the last tag. - self._list_tags = [] # If writing HTML for lists, the current list tags. - self._table_status = None # Where we are in outputting an HTML table. - - # GitHub doesn't support HTML comments, so as a workaround we give - # a bogus and empty tag, which renders as nothing. - self._in_comment = False - - def HandleHeaderOpen(self, input_line, output_stream, header_level): - """Handle the output for opening a header. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - header_level: The header level. - """ - if self._in_html: - tag = u"h{0}".format(header_level) - self.HandleHtmlOpen(input_line, output_stream, tag, {}, False) - else: - self._Write("#" * header_level + " ", output_stream) - - def HandleHeaderClose( - self, - input_line, - output_stream, - header_level): - """Handle the output for closing a header. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - header_level: The header level. - """ - if self._in_html: - tag = u"h{0}".format(header_level) - self.HandleHtmlClose(input_line, output_stream, tag) - else: - if self._symmetric_headers: - self._Write(" " + "#" * header_level, output_stream) - - def HandleHRule(self, input_line, output_stream): - """Handle the output for a horizontal rule. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - if self._in_html: - self.HandleHtmlOpen(input_line, output_stream, "hr", {}, True) - else: - # One newline needed before to separate from text, and not make a header. - self._Write("\n---\n", output_stream) - - def HandleCodeBlockOpen(self, input_line, output_stream, specified_language): - """Handle the output for starting a code block. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - specified_language: Language for the code block, or None. - """ - if self._in_html: - self._PrintHtmlWarning(input_line, "Code") - self.HandleHtmlOpen(input_line, output_stream, "pre", {}, False) - self.HandleHtmlOpen(input_line, output_stream, "code", {}, False) - else: - if not specified_language: - specified_language = "" - self._Write(u"```{0}\n".format(specified_language), output_stream) - self._in_code_block = True - - def HandleCodeBlockClose(self, input_line, output_stream): - """Handle the output for ending a code block. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - self._in_code_block = False - if self._in_html: - self.HandleHtmlClose(input_line, output_stream, "code") - self.HandleHtmlClose(input_line, output_stream, "pre") - else: - self._Write("```", output_stream) - - def HandleNumericListOpen( - self, - input_line, - output_stream, - indentation_level): - """Handle the output for the opening of a numeric list item. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - indentation_level: The indentation level for the item. - """ - if self._in_html: - self._HandleHtmlListOpen( - input_line, - output_stream, - indentation_level, - "Numeric list") - else: - self._Indent(output_stream, indentation_level) - # Just using any number implies a numbered item, - # so we take the easy route. - self._Write("1. ", output_stream) - - def HandleBulletListOpen( - self, - input_line, - output_stream, - indentation_level): - """Handle the output for the opening of a bulleted list item. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - indentation_level: The indentation level for the item. - """ - if self._in_html: - self._HandleHtmlListOpen( - input_line, - output_stream, - indentation_level, - "Bulleted list") - else: - self._Indent(output_stream, indentation_level) - self._Write("* ", output_stream) - - def HandleBlockQuoteOpen( - self, - input_line, - output_stream, - indentation_level): - """Handle the output for the opening of a block quote line. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - indentation_level: The indentation level for the item. - """ - if self._in_html: - self._HandleHtmlListOpen( - input_line, - output_stream, - indentation_level, - "Blockquote") - else: - if self._last_blockquote_indent > indentation_level: - self._Write("\n", output_stream) - self._last_blockquote_indent = indentation_level - # Blockquotes are nested not by indentation but by nesting. - self._Write("> " * indentation_level, output_stream) - - def HandleListClose(self, input_line, output_stream): - """Handle the output for the closing of a list. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - if self._in_html: - self._HandleHtmlListClose(input_line, output_stream) - - def HandleParagraphBreak(self, unused_input_line, output_stream): - """Handle the output for a new paragraph. - - Args: - unused_input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - self._Write("\n", output_stream) - - def HandleBoldOpen(self, input_line, unused_output_stream): - """Handle the output for starting bold formatting. - - Args: - input_line: Current line number being processed. - unused_output_stream: Output Markdown file. - """ - if self._in_html: - self._PrintHtmlWarning(input_line, "Bold") - - # Open up another buffer. - self._format_buffer.append("") - - def HandleBoldClose(self, input_line, output_stream): - """Handle the output for ending bold formatting. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - self._HandleFormatClose(input_line, output_stream, "Bold") - - def HandleItalicOpen(self, input_line, unused_output_stream): - """Handle the output for starting italic formatting. - - Args: - input_line: Current line number being processed. - unused_output_stream: Output Markdown file. - """ - if self._in_html: - self._PrintHtmlWarning(input_line, "Italic") - - # Open up another buffer. - self._format_buffer.append("") - - def HandleItalicClose(self, input_line, output_stream): - """Handle the output for ending italic formatting. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - self._HandleFormatClose(input_line, output_stream, "Italic") - - def HandleStrikethroughOpen(self, input_line, unused_output_stream): - """Handle the output for starting strikethrough formatting. - - Args: - input_line: Current line number being processed. - unused_output_stream: Output Markdown file. - """ - if self._in_html: - self._PrintHtmlWarning(input_line, "Strikethrough") - - # Open up another buffer. - self._format_buffer.append("") - - def HandleStrikethroughClose(self, input_line, output_stream): - """Handle the output for ending strikethrough formatting. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - self._HandleFormatClose(input_line, output_stream, "Strikethrough") - - def HandleSuperscript(self, unused_input_line, output_stream, text): - """Handle the output for superscript text. - - Args: - unused_input_line: Current line number being processed. - output_stream: Output Markdown file. - text: The text to output. - """ - # Markdown currently has no dedicated markup for superscript. - self._Write(u"{0}".format(text), output_stream) - - def HandleSubscript(self, unused_input_line, output_stream, text): - """Handle the output for subscript text. - - Args: - unused_input_line: Current line number being processed. - output_stream: Output Markdown file. - text: The text to output. - """ - # Markdown currently has no dedicated markup for subscript. - self._Write(u"{0}".format(text), output_stream) - - def HandleInlineCode(self, input_line, output_stream, code): - """Handle the output for a code block. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - code: The code inlined. - """ - if self._in_html: - self.HandleHtmlOpen(input_line, output_stream, "code", {}, False) - self.HandleText(input_line, output_stream, cgi.escape(code)) - self.HandleHtmlClose(input_line, output_stream, "code") - else: - # To render backticks within inline code, the surrounding tick count - # must be one greater than the number of consecutive ticks in the code. - # E.g.: - # `this is okay, no ticks in the code` - # `` `one consecutive tick in the code implies two in the delimiter` `` - # ``` `` `and two consecutive ticks in here implies three -> ``` - max_consecutive_ticks = 0 - consecutive_ticks = 0 - for char in code: - if char == "`": - consecutive_ticks += 1 - max_consecutive_ticks = max(max_consecutive_ticks, consecutive_ticks) - else: - consecutive_ticks = 0 - - surrounding_ticks = "`" * (max_consecutive_ticks + 1) - self._Write(u"{0}{1}{0}".format(surrounding_ticks, code), output_stream) - - def HandleTableCellBorder(self, input_line, output_stream): - """Handle the output for a table cell border. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - if self._in_html: - if not self._table_status: - # Starting a new table. - self._PrintHtmlWarning(input_line, "Table") - self.HandleHtmlOpen(input_line, output_stream, "table", {}, False) - self.HandleHtmlOpen(input_line, output_stream, "thead", {}, False) - self.HandleHtmlOpen(input_line, output_stream, "th", {}, False) - self._table_status = "header" - elif self._table_status == "header": - # Header cell. Close the previous cell, open the next one. - self.HandleHtmlClose(input_line, output_stream, "th") - self.HandleHtmlOpen(input_line, output_stream, "th", {}, False) - elif self._table_status == "rowstart": - # First row cell. - self.HandleHtmlOpen(input_line, output_stream, "tr", {}, False) - self.HandleHtmlOpen(input_line, output_stream, "td", {}, False) - self._table_status = "row" - elif self._table_status == "row": - # Row cell. Close the previous cell, open the next one. - self.HandleHtmlClose(input_line, output_stream, "td") - self.HandleHtmlOpen(input_line, output_stream, "td", {}, False) - else: - self._Write("|", output_stream) - - def HandleTableRowEnd(self, input_line, output_stream): - """Handle the output for a table row end. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - if self._in_html: - if self._table_status == "header": - # Closing header. Close the previous cell and header, start the body. - self.HandleHtmlClose(input_line, output_stream, "th") - self.HandleHtmlClose(input_line, output_stream, "thead") - self.HandleHtmlOpen(input_line, output_stream, "tbody", {}, False) - elif self._table_status == "row": - # Closing row. Close the previous cell and row. - self.HandleHtmlClose(input_line, output_stream, "td") - self.HandleHtmlClose(input_line, output_stream, "tr") - self._table_status = "rowstart" - else: - self._Write("|", output_stream) - - def HandleTableClose(self, input_line, output_stream): - """Handle the output for a table end. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - if self._in_html: - # HandleTableRowEnd will have been called by this point. - # All we need to do is close the body and table. - self.HandleHtmlClose(input_line, output_stream, "tbody") - self.HandleHtmlClose(input_line, output_stream, "table") - self._table_status = None - - def HandleTableHeader(self, input_line, output_stream, columns): - """Handle the output for starting a table header. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - columns: Column sizes. - """ - if self._in_html: - return - - self.HandleText(input_line, output_stream, "\n") - - for column_width in columns: - self.HandleTableCellBorder(input_line, output_stream) - - # Wiki tables are left-aligned, which takes one character to specify. - self._Write(u":{0}".format("-" * (column_width - 1)), output_stream) - - self.HandleTableCellBorder(input_line, output_stream) - - def HandleLink(self, input_line, output_stream, target, description): - """Handle the output of a link. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - target: The target URL of the link. - description: The description for the target. - """ - # There are six cases to handle in general: - # 1. Image link with image description: - # Link to image, using image from description as content. - # 2. Image link with non-image description: - # Link to image, using description text as content. - # 3. Image link with no description: - # Inline image. - # 4. URL link with image description: - # Link to URL, using image from description as content. - # 5. URL link with non-image description: - # Link to URL, using description text as content. - # 6. URL link with no description: - # Link to URL, using URL as content. - # Only in case 3 is no actual link present. - is_image = target.endswith(self._IMAGE_EXTENSIONS) - is_image_description = (description and - description.startswith(self._IMAGE_URL_SCHEMAS) and - description.endswith(self._IMAGE_EXTENSIONS)) - - if self._in_html: - self._PrintHtmlWarning(input_line, "Link") - - # Handle inline image case. - if is_image and not description: - self.HandleHtmlOpen( - input_line, - output_stream, - "img", - {"src": target}, - True) - else: - # Handle link cases. - self.HandleHtmlOpen( - input_line, - output_stream, - "a", - {"href": target}, - False) - if is_image_description: - self.HandleHtmlOpen( - input_line, - output_stream, - "img", - {"src": description}, - True) - else: - description = description or target - self._Write(cgi.escape(description), output_stream) - self.HandleHtmlClose(input_line, output_stream, "a") - else: - # If description is None, this means that only the URL was given. We'd - # like to let GFM auto-link it, because it's prettier. However, while Wiki - # syntax would auto-link a variety of URL schemes, GFM only supports http - # and https. In other cases and in the case of images, we explicitly link. - is_autolinkable = target.startswith(self._GFM_AUTO_URL_SCHEMAS) - autolink = (description is None) and is_autolinkable and (not is_image) - - if autolink: - self._Write(target, output_stream) - else: - # If the descriptive text looks like an image URL, Wiki syntax would - # make the link description an inlined image. We do this by setting - # the output description to the syntax used to inline an image. - if is_image_description: - description = u"![]({0})".format(description) - elif description: - description = self._Escape(description) - else: - description = target - is_image_description = is_image - - # Prefix ! if linking to an image without a text description. - prefix = "!" if is_image and is_image_description else "" - - output = u"{0}[{1}]({2})".format(prefix, description, target) - self._Write(output, output_stream) - - def HandleWiki(self, input_line, output_stream, target, text): - """Handle the output of a wiki link. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - target: The target URL of the link. - text: The description for the target. - """ - # A wiki link is just like a regular link, except under the wiki directory. - # At this point we make the text equal to the original target if unset. - # We do however append ".md", assuming the wiki files now have that extension. - self.HandleLink(input_line, output_stream, target + ".md", text or target) - - def HandleIssue(self, input_line, output_stream, prefix, issue): - """Handle the output for an auto-linked issue. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - prefix: The text that came before the issue number. - issue: The issue number. - """ - handled = False - - # Preferred handler is to map the Google Code issue to a GitHub issue. - if self._issue_map and issue in self._issue_map: - migrated_issue_url = self._issue_map[issue] - migrated_issue = migrated_issue_url.rsplit("/", 1)[1] - self.HandleLink( - input_line, - output_stream, - migrated_issue_url, - u"{0}{1}".format(prefix, migrated_issue)) - handled = True - - instructions = (u"In the output, it has been linked to the migrated issue " - "on GitHub: {0}. Please verify this issue on GitHub " - "corresponds to the original issue on Google Code. " - .format(migrated_issue)) - elif self._issue_map: - instructions = ("However, it was not found in the issue migration map; " - "please verify that this issue has been correctly " - "migrated to GitHub and that the issue mapping is put " - "in the issue migration map file. ") - else: - instructions = ("However, no issue migration map was specified. You " - "can use issue_migration.py to migrate your Google " - "Code issues to GitHub, and supply the resulting issue " - "migration map file to this converter. Your old issues " - "will be auto-linked to your migrated issues. ") - - # If we couldn't handle it in the map, try linking to the old issue. - if not handled and self._project: - old_link = (u"https://code.google.com/p/{0}/issues/detail?id={1}" - .format(self._project, issue)) - self.HandleLink( - input_line, - output_stream, - old_link, - u"{0}{1}".format(prefix, issue)) - handled = True - - instructions += (u"As a placeholder, the text has been modified to " - "link to the original Google Code issue page:\n\t{0}" - .format(old_link)) - elif not handled: - instructions += ("Additionally, because no project name was specified " - "the issue could not be linked to the original Google " - "Code issue page.") - - # Couldn't map it to GitHub nor could we link to the old issue. - if not handled: - output = u"{0}{1} (on Google Code)".format(prefix, issue) - self._Write(output, output_stream) - handled = True - - instructions += (u"The auto-link has been removed and the text has been " - "modified from '{0}{1}' to '{2}'." - .format(prefix, issue, output)) - - self._warning_method( - input_line, - u"Issue {0} was auto-linked. {1}".format(issue, instructions)) - - def HandleRevision(self, input_line, output_stream, prefix, revision): - """Handle the output for an auto-linked issue. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - prefix: The text that came before the revision number. - revision: The revision number. - """ - # Google Code only auto-linked revision numbers, not hashes, so - # revision auto-linking cannot be done for the conversion. - if self._project: - old_link = (u"https://code.google.com/p/{0}/source/detail?r={1}" - .format(self._project, revision)) - self.HandleLink( - input_line, - output_stream, - old_link, - u"{0}{1}".format(prefix, revision)) - - instructions = (u"As a placeholder, the text has been modified to " - "link to the original Google Code source page:\n\t{0}" - .format(old_link)) - else: - output = u"{0}{1} (on Google Code)".format(prefix, revision) - self._Write(output, output_stream) - - instructions = (u"Additionally, because no project name was specified " - "the revision could not be linked to the original " - "Google Code source page. The auto-link has been removed " - "and the text has been modified from '{0}{1}' to '{2}'." - .format(prefix, revision, output)) - - self._warning_method( - input_line, - u"Revision {0} was auto-linked. SVN revision numbers are not sensible " - "in Git; consider updating this link or removing it altogether. {1}" - .format(revision, instructions)) - - def HandleHtmlOpen( - self, - unused_input_line, - output_stream, - html_tag, - params, - has_end): - """Handle the output for an opening HTML tag. - - Args: - unused_input_line: Current line number being processed. - output_stream: Output Markdown file. - html_tag: The HTML tag name. - params: The parameters for the tag. - has_end: True if the tag was self-closed. - """ - core_params = self._SerializeHtmlParams(params) - core = u"{0}{1}".format(html_tag, core_params) - - if has_end: - output = u"<{0} />".format(core) - else: - output = u"<{0}>".format(core) - self._in_html += 1 - - self._Write(output, output_stream) - - self._has_written_text = False - - def HandleHtmlClose(self, unused_input_line, output_stream, html_tag): - """Handle the output for an closing HTML tag. - - Args: - unused_input_line: Current line number being processed. - output_stream: Output Markdown file. - html_tag: The HTML tag name. - """ - self._Write(u"".format(html_tag), output_stream) - self._in_html -= 1 - self._has_written_text = False - - def HandleGPlusOpen(self, input_line, output_stream, unused_params): - """Handle the output for opening a +1 button. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - unused_params: The parameters for the tag. - """ - self._warning_method( - input_line, - "A Google+ +1 button was embedded on this page, but GitHub does not " - "currently support this. Should it become supported in the future, " - "see https://developers.google.com/+/web/+1button/ for more " - "information.\nIt has been removed.") - - def HandleGPlusClose(self, unused_input_line, unused_output_stream): - """Handle the output for closing a +1 button. - - Args: - unused_input_line: Current line number being processed. - unused_output_stream: Output Markdown file. - """ - pass - - def HandleCommentOpen(self, input_line, output_stream): - """Handle the output for opening a comment. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - self._warning_method( - input_line, - "A comment was used in the wiki file, but GitHub does not currently " - "support Markdown or HTML comments. As a work-around, the comment will " - "be placed in a bogus and empty tag.") - self._Write("", output_stream) - - def HandleVideoOpen(self, input_line, output_stream, video_id, width, height): - """Handle the output for opening a video. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - video_id: The video ID to play. - width: Width of the resulting widget. - height: Height of the resulting widget. - """ - self._warning_method( - input_line, - "GFM does not support embedding the YouTube player directly. Instead " - "an image link to the video is being used, maintaining sizing options.") - - output = self._VIDEO_TEMPLATE.format(video_id, width, height) - self._Write(output, output_stream) - - def HandleVideoClose(self, unused_input_line, output_stream): - """Handle the output for closing a video. - - Args: - unused_input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - # Everything was handled on the open side. - pass - - def HandleText(self, unused_input_line, output_stream, text): - """Handle the output of raw text. - - Args: - unused_input_line: Current line number being processed. - output_stream: Output Markdown file. - text: The text to output. - """ - self._Write(text, output_stream) - self._has_written_text = True - - def HandleEscapedText(self, input_line, output_stream, text): - """Handle the output of text, which should be escaped for Markdown. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - text: The text to output. - """ - # If we're in HTML, Markdown isn't processed anyway. - if self._in_html: - self.HandleText(input_line, output_stream, text) - else: - self.HandleText(input_line, output_stream, self._Escape(text)) - - def _PrintHtmlWarning(self, input_line, kind): - """Warn about HTML translation being performed. - - Args: - input_line: Current line number being processed. - kind: The kind of tag being changed. - """ - self._warning_method( - input_line, - u"{0} markup was used within HTML tags. Because GitHub does not " - "support this, the tags have been translated to HTML. Please verify " - "that the formatting is correct.".format(kind)) - - def _HandleHtmlListOpen( - self, - input_line, - output_stream, - indentation_level, - kind): - """Handle the output for opening an HTML list. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - indentation_level: The indentation level for the item. - kind: The kind of list being opened. - """ - # Determine if this is a new list, and if a previous list was closed. - if self._list_tags: - top_tag = self._list_tags[-1] - if top_tag["indent"] != indentation_level: - # Opening a new nested list. Indentation level will always be greater, - # because for it to have gone down, the list would have been closed. - new_list = True - closing = False - elif top_tag["kind"] != kind: - # Closed the previous list, started a new one. - new_list = True - closing = True - else: - # Same list, already opened. - new_list = False - closing = False - else: - new_list = True - closing = False - - # If we need to, close the prior list. - if closing: - self._HandleHtmlListClose(input_line, output_stream) - - # Grab the tags we'll be using. - list_tag = self._HTML_LIST_TAGS[kind]["ListTag"] - item_tag = self._HTML_LIST_TAGS[kind]["ItemTag"] - - # If this is a new list, note it in the stack and open it. - if new_list: - new_tag = { - "indent": indentation_level, - "kind": kind, - } - self._list_tags.append(new_tag) - - self._PrintHtmlWarning(input_line, kind) - self.HandleHtmlOpen(input_line, output_stream, list_tag, {}, False) - else: - # Not a new list, close the previously outputted item. - if item_tag: - self.HandleHtmlClose(input_line, output_stream, item_tag) - - # Open up a new list item - if item_tag: - self.HandleHtmlOpen(input_line, output_stream, item_tag, {}, False) - - def _HandleHtmlListClose(self, input_line, output_stream): - """Handle the output for closing an HTML list. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - """ - # Fix index error if list_tags is empty. - if len(self._list_tags) == 0: - self._warning_method(input_line, "HtmlListClose without list_tags?") - self._list_tags = [ { "indent": 0, "kind": "Bulleted list" } ] - top_tag = self._list_tags[-1] - kind = top_tag["kind"] - self._list_tags.pop() - - # Grab the tags we'll be using. - list_tag = self._HTML_LIST_TAGS[kind]["ListTag"] - item_tag = self._HTML_LIST_TAGS[kind]["ItemTag"] - - # Close the previously outputted item and the list. - if item_tag: - self.HandleHtmlClose(input_line, output_stream, item_tag) - - self.HandleHtmlClose(input_line, output_stream, list_tag) - - def _HandleFormatClose(self, input_line, output_stream, kind): - """Handle the output of a closing format tag. - - Args: - input_line: Current line number being processed. - output_stream: Output Markdown file. - kind: The formatting kind. - """ - if self._format_buffer: - # End redirection. - format_buffer = self._format_buffer[-1] - self._format_buffer.pop() - - # Don't do anything if we didn't buffer, or it was only whitespace. - format_buffer = format_buffer.strip() - if not format_buffer: - return - - if self._in_html: - tag = self._HTML_FORMAT_TAGS[kind]["HTML"] - self.HandleHtmlOpen(input_line, output_stream, tag, {}, False) - self.HandleText(input_line, output_stream, format_buffer) - self.HandleHtmlClose(input_line, output_stream, tag) - else: - tag = self._HTML_FORMAT_TAGS[kind]["Markdown"] - self._Write(u"{0}{1}{0}".format(tag, format_buffer), output_stream) - - else: - self._warning_method(input_line, u"Re-closed '{0}', ignoring.".format(tag)) - - def _Indent(self, output_stream, indentation_level): - """Output indentation. - - Args: - output_stream: Output Markdown file. - indentation_level: Number of indentations to output. - """ - self._Write(self._SINGLE_INDENTATION * indentation_level, output_stream) - - def _Escape(self, text): - """Escape Wiki text to be suitable in Markdown. - - Args: - text: Input Wiki text. - Returns: - Escaped text for Markdown. - """ - text = text.replace("*", r"\*") - text = text.replace("_", r"\_") - - # If we find a plugin-like bit of text, escape the angle-brackets. - for plugin_re in [constants.PLUGIN_RE, constants.PLUGIN_END_RE]: - while plugin_re.search(text): - match = plugin_re.search(text) - before_match = text[:match.start()] - after_match = text[match.end():] - escaped_match = match.group(0).replace("<", "<").replace(">", ">") - text = u"{0}{1}{2}".format(before_match, escaped_match, after_match) - - # In Markdown, if a newline is preceeded by two spaces it breaks the line. - # For Wiki text, this is not the case, so we strip such endings off. - while text.endswith(" \n"): - text = text[:-len(" \n")] + "\n" - - return text - - def _SerializeHtmlParams(self, params): - """Serialize parameters for an HTML tag. - - Args: - params: The parameters for the tag. - Returns: - Serialized parameters. - """ - core_params = "" - for name, value in params.items(): - if "'" not in value: - quote = "'" - else: - quote = "\"" - core_params += u" {0}={1}{2}{1}".format(name, quote, value) - - return core_params - - def _Write(self, text, output_stream): - """Write text to the output stream, taking into account any redirection. - - Args: - text: Input raw text. - output_stream: Output Markdown file. - """ - if not text: - return - - if not self._in_comment and self._in_html: - if self._in_code_block: - text = cgi.escape(text) - - if self._in_code_block or self._has_written_text: - text = text.replace("\n", "
\n") - - if self._in_comment: - text = text.replace("'", "\"") - - if self._format_buffer: - # Buffering is occuring, add to buffer. - self._format_buffer[-1] += text - else: - # No buffering occuring, just output it. - output_stream.write(text) diff --git a/wiki_to_md/impl/pragma_handler.py b/wiki_to_md/impl/pragma_handler.py deleted file mode 100644 index f2f12c6..0000000 --- a/wiki_to_md/impl/pragma_handler.py +++ /dev/null @@ -1,66 +0,0 @@ -# Copyright 2014 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Handles converting of pragmas.""" - - -class PragmaHandler(object): - """Class that handles the conversion of pragmas.""" - - def __init__(self, warning_method): - """Create a pragma handler. - - Args: - warning_method: A function to call to display a warning message. - """ - self._warning_method = warning_method - - def HandlePragma(self, - input_line, - unused_output_stream, - pragma_type, - pragma_value): - """Handle a parsed pragma directive. - - Args: - input_line: The line number this match occurred on. - unused_output_stream: Output Markdown file. - pragma_type: The pragma's type. - pragma_value: The pragma's value, trimmed. - """ - # There is no meaningful equivalent to any of the pragmas - # Google Code supports, so simply notify the user a pragma - # was matched and that they might want to do something about it. - if pragma_type == "summary": - self._warning_method( - input_line, - u"A summary pragma was used for this wiki:\n" - "\t{0}\n" - "Consider moving it to an introductory paragraph." - .format(pragma_value)) - elif pragma_type == "sidebar": - self._warning_method( - input_line, - u"A sidebar pragma was used for this wiki:\n" - "\t{0}\n" - "The Gollum wiki system supports sidebars, and by converting " - "{0}.wiki to _Sidebar.md it can be used as a sidebar.\n" - "See https://github.com/gollum/gollum/wiki for more information." - .format(pragma_value)) - else: - self._warning_method( - input_line, - u"The following pragma has been ignored:\n" - "\t#{0} {1}\n" - "Consider expressing the same information in a different manner." - .format(pragma_type, pragma_value)) diff --git a/wiki_to_md/wiki2gfm.py b/wiki_to_md/wiki2gfm.py deleted file mode 100755 index 8ee84ec..0000000 --- a/wiki_to_md/wiki2gfm.py +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright 2014 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Tool to convert Google Code Wiki files to GitHub-flavored Markdown. - - Reference for Google Code Wiki: - https://code.google.com/p/support/wiki/WikiSyntax - - Reference for Github-flavored Markdown: - https://help.github.com/articles/github-flavored-markdown - - The conversion process is not always directly possible; for example, - wiki pragma statements have no direct equivalent for GFM. In cases - where no direct conversion can be made, or the input may have unexpected - output, a warning will be issued. -""" -import argparse - -import codecs -import os -import sys - -from impl import converter as converter_mod -from impl import formatting_handler as formatting_handler_mod -from impl import pragma_handler as pragma_handler_mod - - -def PrintWarning(input_line, message): - """Print a warning. - - When a conversion cannot be done or may be unreliable/inexact, - a warning will be printed to stdout notifying the user of this. - - Args: - input_line: The line number this warning occurred on. - message: The warning message. - """ - print u"Warning (line {0} of input file):\n{1}\n".format(input_line, message) - - -def main(args): - """The main function. - - Args: - args: The command line arguments. - """ - parser = argparse.ArgumentParser( - description="Converts a Google Code wiki page to GitHub-flavored " - "Markdown.") - - parser.add_argument("--input_file", required=True, - help="The input Google Code Wiki file") - parser.add_argument("--output_file", required=True, - help="The output GitHub-flavored Markdown file") - parser.add_argument("--project", required=False, - help="The name of the project for the Wiki") - parser.add_argument("--wikipages_list", nargs="*", - help="The list of wiki pages that are assumed to exist " - "for the purpose of auto-linking to other pages") - parser.add_argument("--wikipages_path", nargs="*", - help="The list of paths containing wiki pages that are " - "assumed to exist for the purpose of auto-linking to " - "other pages") - symmetric_headers_help = ("Controls if the output of header level " - "indicators are made symmetric. E.g. '### Header' " - "if disabled, and '### Header ###' if enabled") - parser.add_argument("--symmetric_headers", dest="symmetric_headers", - action="store_true", help=symmetric_headers_help) - parser.add_argument("--no_symmetric_headers", dest="symmetric_headers", - action="store_false", help=symmetric_headers_help) - parser.set_defaults(feature=False) - - parsed_args, unused_unknown_args = parser.parse_known_args(args) - - with codecs.open(parsed_args.input_file, "rU", "utf-8") as input_stream: - with codecs.open(parsed_args.output_file, "wU", "utf-8") as output_stream: - # Create the master list of wiki pages assumed to exist. - wikipages = parsed_args.wikipages_list or [] - wikipages.append(parsed_args.input_file) - - if parsed_args.wikipages_path: - # Add all the .wiki files in all the given paths. - for path in parsed_args.wikipages_path: - for f in os.listdir(path): - if f.endswith(".wiki"): - wikipages.append(f[:-len(".wiki")]) - - # Fill this will a mapping from Google Code issue - # to GitHub issue to automate that conversion. - issue_map = {} - - # Prepare the handlers and converter. - pragma_handler = pragma_handler_mod.PragmaHandler(PrintWarning) - formatting_handler = formatting_handler_mod.FormattingHandler( - PrintWarning, - parsed_args.project, - issue_map, - parsed_args.symmetric_headers) - converter = converter_mod.Converter( - pragma_handler, - formatting_handler, - PrintWarning, - parsed_args.project, - wikipages) - - # And perform the conversion. - converter.Convert(input_stream, output_stream) - - -if __name__ == "__main__": - main(sys.argv) diff --git a/wiki_to_md/wiki2gfm_test.py b/wiki_to_md/wiki2gfm_test.py deleted file mode 100644 index 845385d..0000000 --- a/wiki_to_md/wiki2gfm_test.py +++ /dev/null @@ -1,803 +0,0 @@ -# Copyright 2014 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Tests for wiki2gfm.""" -import codecs -import StringIO -import unittest - -from impl import converter -from impl import formatting_handler -from impl import pragma_handler - - -class BaseTest(unittest.TestCase): - """Base test for wiki2gfm tests.""" - - def setUp(self): - """Create a base test.""" - self.warnings = [] - self.output = StringIO.StringIO() - - self.pragma_handler = pragma_handler.PragmaHandler(self._TrackWarning) - self.formatting_handler = formatting_handler.FormattingHandler( - self._TrackWarning, - project="test", - issue_map={123: "https://github.com/abcxyz/test/issues/789"}, - symmetric_headers=False) - self.converter = converter.Converter( - self.pragma_handler, - self.formatting_handler, - self._TrackWarning, - project="test", - wikipages=["TestPage"]) - - def assertOutput(self, expected_output): - """Assert that specific output was written. - - Args: - expected_output: The expected value of the output. - """ - self.assertEquals(expected_output, self.output.getvalue()) - - def assertNoOutput(self, expected_output): - self.assertNotEqual(expected_output, self.output.getvalue()) - - def assertWarning(self, warning_contents, occurrences=1): - """Assert that a warning was issued containing the given contents. - - This searches all tracked warnings for the contents. - - Args: - warning_contents: Text that the warning was expected to contain. - occurrences: The number of occurrences of the warning contents. - """ - occurrences_found = 0 - for warning in self.warnings: - if warning_contents in warning[1]: - occurrences_found += 1 - - if occurrences_found != occurrences: - self.fail("Failed to find '{0}' in {1} warnings (found it in {2})." - .format(warning_contents, occurrences, occurrences_found)) - - def assertNoWarnings(self): - """Assert that no warnings were issued.""" - self.assertListEqual([], self.warnings) - - def _TrackWarning(self, input_line, message): - """Track a warning by storing it in memory. - - Args: - input_line: Line the warning was issued on. - message: The warning message. - """ - self.warnings.append((input_line, message)) - - -class TestPragmaHandler(BaseTest): - """Tests the pragma handler.""" - - def testSummaryPragmaGivesWarning(self): - self.pragma_handler.HandlePragma(1, self.output, "summary", "abc") - - self.assertWarning("summary") - - def testSidebarPragmaGivesWarning(self): - self.pragma_handler.HandlePragma(1, self.output, "sidebar", "abc") - - self.assertWarning("sidebar") - - def testUnknownPragmaGivesWarning(self): - self.pragma_handler.HandlePragma(1, self.output, "fail!", "abc") - - self.assertWarning("fail!") - - -class TestFormattingHandler(BaseTest): - """Tests the formatting handler.""" - - def testHandleHeaderOpen(self): - self.formatting_handler.HandleHeaderOpen(1, self.output, 3) - - self.assertOutput("### ") - self.assertNoWarnings() - - def testHandleHeaderOpenInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleHeaderOpen(1, self.output, 3) - - self.assertOutput("

") - self.assertNoWarnings() - - def testHandleHeaderClose(self): - self.formatting_handler.HandleHeaderClose(1, self.output, 3) - - self.assertOutput("") # No header closing markup by default. - self.assertNoWarnings() - - def testHandleHeaderCloseInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleHeaderClose(1, self.output, 3) - - self.assertOutput("

") - self.assertNoWarnings() - - def testHandleHeaderCloseSymmetric(self): - self.formatting_handler._symmetric_headers = True - self.formatting_handler.HandleHeaderClose(1, self.output, 3) - - self.assertOutput(" ###") - self.assertNoWarnings() - - def testHandleHeaderCloseSymmetricInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler._symmetric_headers = True - self.formatting_handler.HandleHeaderClose(1, self.output, 3) - - self.assertOutput("") - self.assertNoWarnings() - - def testHandleHRule(self): - self.formatting_handler.HandleHRule(1, self.output) - - self.assertOutput("\n---\n") - self.assertNoWarnings() - - def testHandleHRuleInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleHRule(1, self.output) - - self.assertOutput("
") - self.assertNoWarnings() - - def testHandleCodeBlockOpen(self): - self.formatting_handler.HandleCodeBlockOpen(1, self.output, None) - - self.assertOutput("```\n") - self.assertNoWarnings() - - def testHandleCodeBlockOpenInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleCodeBlockOpen(1, self.output, None) - - self.assertOutput("
")
-    self.assertWarning("Code markup was used")
-
-  def testHandleCodeBlockOpenWithLanguage(self):
-    self.formatting_handler.HandleCodeBlockOpen(1, self.output, "idris")
-
-    self.assertOutput("```idris\n")
-    self.assertNoWarnings()
-
-  def testHandleCodeBlockOpenWithLanguageInHtml(self):
-    self.formatting_handler._in_html = 1
-    self.formatting_handler.HandleCodeBlockOpen(1, self.output, "idris")
-
-    self.assertOutput("
")
-    self.assertWarning("Code markup was used")
-
-  def testHandleCodeBlockClose(self):
-    self.formatting_handler.HandleCodeBlockClose(1, self.output)
-
-    self.assertOutput("```")
-    self.assertNoWarnings()
-
-  def testHandleCodeBlockCloseInHtml(self):
-    self.formatting_handler._in_html = 1
-    self.formatting_handler.HandleCodeBlockClose(1, self.output)
-
-    self.assertOutput("
") - self.assertNoWarnings() - - def testHandleNumericList(self): - self.formatting_handler.HandleNumericListOpen(1, self.output, 1) - self.formatting_handler.HandleText(1, self.output, "a\n") - self.formatting_handler.HandleNumericListOpen(2, self.output, 1) - self.formatting_handler.HandleText(2, self.output, "b\n") - self.formatting_handler.HandleNumericListOpen(3, self.output, 2) - self.formatting_handler.HandleText(3, self.output, "c\n") - self.formatting_handler.HandleListClose(4, self.output) # Closing 2. - self.formatting_handler.HandleNumericListOpen(4, self.output, 1) - self.formatting_handler.HandleText(4, self.output, "d\n") - self.formatting_handler.HandleListClose(5, self.output) # Closing 1. - - self.assertOutput(" 1. a\n 1. b\n 1. c\n 1. d\n") - self.assertNoWarnings() - - def testHandleNumericListInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleNumericListOpen(1, self.output, 1) - self.formatting_handler.HandleText(1, self.output, "a\n") - self.formatting_handler.HandleNumericListOpen(2, self.output, 1) - self.formatting_handler.HandleText(2, self.output, "b\n") - self.formatting_handler.HandleNumericListOpen(3, self.output, 2) - self.formatting_handler.HandleText(3, self.output, "c\n") - self.formatting_handler.HandleListClose(4, self.output) # Closing 2. - self.formatting_handler.HandleNumericListOpen(4, self.output, 1) - self.formatting_handler.HandleText(4, self.output, "d\n") - self.formatting_handler.HandleListClose(5, self.output) # Closing 1. - - self.assertOutput("
  1. a\n
  2. b\n
    1. c\n
  3. " - "
  4. d\n
") - self.assertWarning("Numeric list markup was used", occurrences=2) - - def testHandleBulletList(self): - self.formatting_handler.HandleBulletListOpen(1, self.output, 1) - self.formatting_handler.HandleText(1, self.output, "a\n") - self.formatting_handler.HandleBulletListOpen(2, self.output, 1) - self.formatting_handler.HandleText(2, self.output, "b\n") - self.formatting_handler.HandleBulletListOpen(3, self.output, 2) - self.formatting_handler.HandleText(3, self.output, "c\n") - self.formatting_handler.HandleListClose(4, self.output) # Closing 2. - self.formatting_handler.HandleBulletListOpen(4, self.output, 1) - self.formatting_handler.HandleText(4, self.output, "d\n") - self.formatting_handler.HandleListClose(5, self.output) # Closing 1. - - self.assertOutput(" * a\n * b\n * c\n * d\n") - self.assertNoWarnings() - - def testHandleBulletListInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleBulletListOpen(1, self.output, 1) - self.formatting_handler.HandleText(1, self.output, "a\n") - self.formatting_handler.HandleBulletListOpen(2, self.output, 1) - self.formatting_handler.HandleText(2, self.output, "b\n") - self.formatting_handler.HandleBulletListOpen(3, self.output, 2) - self.formatting_handler.HandleText(3, self.output, "c\n") - self.formatting_handler.HandleListClose(4, self.output) # Closing 2. - self.formatting_handler.HandleBulletListOpen(4, self.output, 1) - self.formatting_handler.HandleText(4, self.output, "d\n") - self.formatting_handler.HandleListClose(5, self.output) # Closing 1. - - self.assertOutput("
  • a\n
  • b\n
    • c\n
  • " - "
  • d\n
") - self.assertWarning("Bulleted list markup was used", occurrences=2) - - def testHandleBlockQuote(self): - self.formatting_handler.HandleBlockQuoteOpen(1, self.output, 1) - self.formatting_handler.HandleText(1, self.output, "a\n") - self.formatting_handler.HandleBlockQuoteOpen(2, self.output, 1) - self.formatting_handler.HandleText(2, self.output, "b\n") - self.formatting_handler.HandleBlockQuoteOpen(3, self.output, 2) - self.formatting_handler.HandleText(3, self.output, "c\n") - self.formatting_handler.HandleListClose(4, self.output) # Closing 2. - self.formatting_handler.HandleBlockQuoteOpen(4, self.output, 1) - self.formatting_handler.HandleText(4, self.output, "d\n") - self.formatting_handler.HandleListClose(5, self.output) # Closing 1. - - self.assertOutput("> a\n> b\n> > c\n\n> d\n") - self.assertNoWarnings() - - def testHandleBlockQuoteInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleBlockQuoteOpen(1, self.output, 1) - self.formatting_handler.HandleText(1, self.output, "a\n") - self.formatting_handler.HandleBlockQuoteOpen(2, self.output, 1) - self.formatting_handler.HandleText(2, self.output, "b\n") - self.formatting_handler.HandleBlockQuoteOpen(3, self.output, 2) - self.formatting_handler.HandleText(3, self.output, "c\n") - self.formatting_handler.HandleListClose(4, self.output) # Closing 2. - self.formatting_handler.HandleBlockQuoteOpen(4, self.output, 1) - self.formatting_handler.HandleText(4, self.output, "d\n") - self.formatting_handler.HandleListClose(5, self.output) # Closing 1. - - self.assertOutput("
a\nb
\n
c\n
" - "d\n
") - self.assertWarning("Blockquote markup was used", occurrences=2) - - def testHandleParagraphBreak(self): - self.formatting_handler.HandleText(1, self.output, "a\n") - self.formatting_handler.HandleParagraphBreak(2, self.output) - self.formatting_handler.HandleText(3, self.output, "b\n") - - self.assertOutput("a\n\nb\n") - self.assertNoWarnings() - - def testHandleParagraphBreakInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleText(1, self.output, "a\n") - self.formatting_handler.HandleParagraphBreak(2, self.output) - self.formatting_handler.HandleText(3, self.output, "b\n") - - self.assertOutput("a\n
\nb
\n") - self.assertNoWarnings() - - def testHandleBold(self): - self.formatting_handler.HandleBoldOpen(1, self.output) - self.formatting_handler.HandleText(2, self.output, "xyz") - self.formatting_handler.HandleBoldClose(3, self.output) - - self.assertOutput("**xyz**") - self.assertNoWarnings() - - def testHandleBoldInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleBoldOpen(1, self.output) - self.formatting_handler.HandleText(2, self.output, "xyz") - self.formatting_handler.HandleBoldClose(3, self.output) - - self.assertOutput("xyz") - self.assertWarning("Bold markup was used") - - def testHandleItalic(self): - self.formatting_handler.HandleItalicOpen(1, self.output) - self.formatting_handler.HandleText(2, self.output, "xyz") - self.formatting_handler.HandleItalicClose(3, self.output) - - self.assertOutput("_xyz_") - self.assertNoWarnings() - - def testHandleItalicInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleItalicOpen(1, self.output) - self.formatting_handler.HandleText(2, self.output, "xyz") - self.formatting_handler.HandleItalicClose(3, self.output) - - self.assertOutput("xyz") - self.assertWarning("Italic markup was used") - - def testHandleStrikethrough(self): - self.formatting_handler.HandleStrikethroughOpen(1, self.output) - self.formatting_handler.HandleText(2, self.output, "xyz") - self.formatting_handler.HandleStrikethroughClose(3, self.output) - - self.assertOutput("~~xyz~~") - self.assertNoWarnings() - - def testHandleStrikethroughInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleStrikethroughOpen(1, self.output) - self.formatting_handler.HandleText(2, self.output, "xyz") - self.formatting_handler.HandleStrikethroughClose(3, self.output) - - self.assertOutput("xyz") - self.assertWarning("Strikethrough markup was used") - - def testHandleSuperscript(self): - self.formatting_handler.HandleSuperscript(1, self.output, "xyz") - - self.assertOutput("xyz") - self.assertNoWarnings() - - def testHandleSuperscriptInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleSuperscript(1, self.output, "xyz") - - self.assertOutput("xyz") - self.assertNoWarnings() - - def testHandleSubscript(self): - self.formatting_handler.HandleSubscript(1, self.output, "xyz") - - self.assertOutput("xyz") - self.assertNoWarnings() - - def testHandleSubscriptInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleSubscript(1, self.output, "xyz") - - self.assertOutput("xyz") - self.assertNoWarnings() - - def testHandleInlineCode(self): - self.formatting_handler.HandleInlineCode(1, self.output, "xyz") - - self.assertOutput("`xyz`") - self.assertNoWarnings() - - def testHandleInlineCodeInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleInlineCode(1, self.output, "xyz") - - self.assertOutput("xyz") - self.assertNoWarnings() - - # Table handling is tested in the Converter tests, - # as the interactions are multiple and handled there. - - def testHandleLink(self): - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com", None) - - self.assertOutput("http://example.com") - self.assertNoWarnings() - - def testHandleLinkInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com", None) - - self.assertOutput("http://example.com") - self.assertWarning("Link markup was used") - - def testHandleLinkWithDescription(self): - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com", "Description") - - self.assertOutput("[Description](http://example.com)") - self.assertNoWarnings() - - def testHandleLinkWithDescriptionInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com", "Description") - - self.assertOutput("Description") - self.assertWarning("Link markup was used") - - def testHandleLinkWithImageDescription(self): - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com", "http://example.com/a.png") - - self.assertOutput("[![](http://example.com/a.png)](http://example.com)") - self.assertNoWarnings() - - def testHandleLinkWithImageDescriptionInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com", "http://example.com/a.png") - - self.assertOutput("" - "") - self.assertWarning("Link markup was used") - - def testHandleImageLink(self): - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com/a.png", None) - - self.assertOutput("![http://example.com/a.png](http://example.com/a.png)") - self.assertNoWarnings() - - def testHandleImageLinkInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com/a.png", None) - - self.assertOutput("") - self.assertWarning("Link markup was used") - - def testHandleImageLinkWithDescription(self): - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com/a.png", "Description") - - self.assertOutput("[Description](http://example.com/a.png)") - self.assertNoWarnings() - - def testHandleImageLinkWithDescriptionInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com/a.png", "Description") - - self.assertOutput("Description") - self.assertWarning("Link markup was used") - - def testHandleImageLinkWithImageDescription(self): - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com/a.png", "http://example.com/b.png") - - self.assertOutput("![![](http://example.com/b.png)]" - "(http://example.com/a.png)") - self.assertNoWarnings() - - def testHandleImageLinkWithImageDescriptionInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleLink( - 1, self.output, "http://example.com/a.png", "http://example.com/b.png") - - self.assertOutput("" - "") - self.assertWarning("Link markup was used") - - def testHandleWiki(self): - self.formatting_handler.HandleWiki(1, self.output, "TestPage", "Test Page") - - self.assertOutput("[Test Page](TestPage.md)") - self.assertNoWarnings() - - def testHandleWikiInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleWiki(1, self.output, "TestPage", "Test Page") - - self.assertOutput("Test Page") - self.assertWarning("Link markup was used") - - def testHandleIssue(self): - self.formatting_handler.HandleIssue(1, self.output, "issue ", 123) - - self.assertOutput("[issue 789](https://github.com/abcxyz/test/issues/789)") - self.assertWarning("Issue 123 was auto-linked") - self.assertWarning("In the output, it has been linked to the " - "migrated issue on GitHub: 789.") - - def testHandleIssueInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleIssue(1, self.output, "issue ", 123) - - self.assertOutput("" - "issue 789") - self.assertWarning("Link markup was used") - self.assertWarning("Issue 123 was auto-linked") - self.assertWarning("In the output, it has been linked to the " - "migrated issue on GitHub: 789.") - - def testHandleIssueNotInMap(self): - self.formatting_handler.HandleIssue(1, self.output, "issue ", 456) - - self.assertOutput("[issue 456](https://code.google.com/p/" - "test/issues/detail?id=456)") - self.assertWarning("Issue 456 was auto-linked") - self.assertWarning("However, it was not found in the issue migration map") - self.assertWarning("As a placeholder, the text has been modified to " - "link to the original Google Code issue page") - - def testHandleIssueNotInMapInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleIssue(1, self.output, "issue ", 456) - - self.assertOutput("issue 456") - self.assertWarning("Link markup was used") - self.assertWarning("Issue 456 was auto-linked") - self.assertWarning("However, it was not found in the issue migration map") - self.assertWarning("As a placeholder, the text has been modified to " - "link to the original Google Code issue page") - - def testHandleIssueNoMap(self): - self.formatting_handler._issue_map = None - self.formatting_handler.HandleIssue(1, self.output, "issue ", 456) - - self.assertOutput("[issue 456](https://code.google.com/p/" - "test/issues/detail?id=456)") - self.assertWarning("Issue 456 was auto-linked") - self.assertWarning("However, no issue migration map was specified") - self.assertWarning("As a placeholder, the text has been modified to " - "link to the original Google Code issue page") - - def testHandleIssueNoMapInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler._issue_map = None - self.formatting_handler.HandleIssue(1, self.output, "issue ", 456) - - self.assertOutput("issue 456") - self.assertWarning("Link markup was used") - self.assertWarning("Issue 456 was auto-linked") - self.assertWarning("However, no issue migration map was specified") - self.assertWarning("As a placeholder, the text has been modified to " - "link to the original Google Code issue page") - - def testHandleIssueNotInMapNoProject(self): - self.formatting_handler._project = None - self.formatting_handler.HandleIssue(1, self.output, "issue ", 456) - - self.assertOutput("issue 456 (on Google Code)") - self.assertWarning("Issue 456 was auto-linked") - self.assertWarning("However, it was not found in the issue migration map") - self.assertWarning("Additionally, because no project name was specified " - "the issue could not be linked to the original Google " - "Code issue page.") - self.assertWarning("The auto-link has been removed") - - def testHandleIssueNotInMapNoProjectInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler._project = None - self.formatting_handler.HandleIssue(1, self.output, "issue ", 456) - - self.assertOutput("issue 456 (on Google Code)") - self.assertWarning("Issue 456 was auto-linked") - self.assertWarning("However, it was not found in the issue migration map") - self.assertWarning("Additionally, because no project name was specified " - "the issue could not be linked to the original Google " - "Code issue page.") - self.assertWarning("The auto-link has been removed") - - def testHandleIssueNoMapNoProject(self): - self.formatting_handler._issue_map = None - self.formatting_handler._project = None - self.formatting_handler.HandleIssue(1, self.output, "issue ", 456) - - self.assertOutput("issue 456 (on Google Code)") - self.assertWarning("Issue 456 was auto-linked") - self.assertWarning("However, no issue migration map was specified") - self.assertWarning("Additionally, because no project name was specified " - "the issue could not be linked to the original Google " - "Code issue page.") - self.assertWarning("The auto-link has been removed") - - def testHandleIssueNoMapNoProjectInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler._issue_map = None - self.formatting_handler._project = None - self.formatting_handler.HandleIssue(1, self.output, "issue ", 456) - - self.assertOutput("issue 456 (on Google Code)") - self.assertWarning("Issue 456 was auto-linked") - self.assertWarning("However, no issue migration map was specified") - self.assertWarning("Additionally, because no project name was specified " - "the issue could not be linked to the original Google " - "Code issue page.") - self.assertWarning("The auto-link has been removed") - - def testHandleRevision(self): - self.formatting_handler.HandleRevision(1, self.output, "revision ", 7) - - self.assertOutput("[revision 7](https://code.google.com/p/" - "test/source/detail?r=7)") - self.assertWarning("Revision 7 was auto-linked") - self.assertWarning("As a placeholder, the text has been modified to " - "link to the original Google Code source page") - - def testHandleRevisionInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleRevision(1, self.output, "revision ", 7) - - self.assertOutput("revision 7") - self.assertWarning("Link markup was used") - self.assertWarning("Revision 7 was auto-linked") - self.assertWarning("As a placeholder, the text has been modified to " - "link to the original Google Code source page") - - def testHandleRevisionNoProject(self): - self.formatting_handler._project = None - self.formatting_handler.HandleRevision(1, self.output, "revision ", 7) - - self.assertOutput("revision 7 (on Google Code)") - self.assertWarning("Revision 7 was auto-linked") - self.assertWarning("Additionally, because no project name was specified " - "the revision could not be linked to the original " - "Google Code source page.") - self.assertWarning("The auto-link has been removed") - - def testHandleRevisionNoProjectInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler._project = None - self.formatting_handler.HandleRevision(1, self.output, "revision ", 7) - - self.assertOutput("revision 7 (on Google Code)") - self.assertWarning("Revision 7 was auto-linked") - self.assertWarning("Additionally, because no project name was specified " - "the revision could not be linked to the original " - "Google Code source page.") - self.assertWarning("The auto-link has been removed") - - def testHandleInHtml(self): - self.formatting_handler.HandleHtmlOpen( - 1, self.output, "tag", {"a": "1", "b": "2"}, False) - self.formatting_handler.HandleText(2, self.output, "xyz") - self.formatting_handler.HandleHtmlClose(3, self.output, "tag") - - self.assertOutput("xyz") - self.assertNoWarnings() - - def testHandleHtmlInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleHtmlOpen( - 1, self.output, "tag", {"a": "1", "b": "2"}, False) - self.formatting_handler.HandleText(2, self.output, "xyz") - self.formatting_handler.HandleHtmlClose(3, self.output, "tag") - - self.assertOutput("xyz") - self.assertNoWarnings() - - def testHandleInHtmlSelfClose(self): - self.formatting_handler.HandleHtmlOpen( - 1, self.output, "tag", {"a": "1", "b": "2"}, True) - - self.assertOutput("") - self.assertNoWarnings() - - def testHandleHtmlSelfCloseInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleHtmlOpen( - 1, self.output, "tag", {"a": "1", "b": "2"}, True) - - self.assertOutput("") - self.assertNoWarnings() - - def testHandleGPlus(self): - self.formatting_handler.HandleGPlusOpen(1, self.output, None) - self.formatting_handler.HandleGPlusClose(1, self.output) - - self.assertNoOutput("(TODO: Link to Google+ page.)") - self.assertWarning("A Google+ +1 button was embedded on this page") - - def testHandleGPlusInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleGPlusOpen(1, self.output, None) - self.formatting_handler.HandleGPlusClose(1, self.output) - - self.assertNoOutput("(TODO: Link to Google+ page.)") - self.assertWarning("A Google+ +1 button was embedded on this page") - - def testHandleComment(self): - self.formatting_handler.HandleCommentOpen(1, self.output) - self.formatting_handler.HandleText(2, self.output, "xyz") - self.formatting_handler.HandleCommentClose(3, self.output) - - self.assertOutput("") - self.assertWarning("A comment was used in the wiki file") - - def testHandleCommentInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleCommentOpen(1, self.output) - self.formatting_handler.HandleText(2, self.output, "xyz") - self.formatting_handler.HandleCommentClose(3, self.output) - - self.assertOutput("") - self.assertWarning("A comment was used in the wiki file") - - def testHandleVideo(self): - self.formatting_handler.HandleVideoOpen( - 1, self.output, "FiARsQSlzDc", 320, 240) - self.formatting_handler.HandleVideoClose(1, self.output) - - self.assertOutput("" - "") - self.assertWarning("GFM does not support embedding the YouTube player") - - def testHandleVideoInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleVideoOpen( - 1, self.output, "FiARsQSlzDc", 320, 240) - self.formatting_handler.HandleVideoClose(1, self.output) - - self.assertOutput("" - "") - self.assertWarning("GFM does not support embedding the YouTube player") - - def testHandleText(self): - self.formatting_handler.HandleText(1, self.output, "xyz") - - self.assertOutput("xyz") - self.assertNoWarnings() - - def testHandleTextInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleText(1, self.output, "xyz") - - self.assertOutput("xyz") - self.assertNoWarnings() - - def testHandleEscapedText(self): - self.formatting_handler.HandleEscapedText(1, self.output, "**_xyz_** ") - - self.assertOutput("\\*\\*\\_xyz\\_\\*\\* <a>") - self.assertNoWarnings() - - def testHandleEscapedTextInHtml(self): - self.formatting_handler._in_html = 1 - self.formatting_handler.HandleEscapedText(1, self.output, "**_xyz_** ") - - self.assertOutput("**_xyz_** ") - self.assertNoWarnings() - - -class TestConverter(BaseTest): - """Tests the converter.""" - - def testExamplePage(self): - with codecs.open("example.wiki", "rU", "utf-8") as example_input: - with codecs.open("example.md", "rU", "utf-8") as example_output: - self.converter.Convert(example_input, self.output) - - self.assertOutput(example_output.read()) - - -if __name__ == "__main__": - unittest.main()