__init__.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # ics2vdir - convert .ics file to vdir directory
  2. #
  3. # Copyright (C) 2020 Fabian Peter Hammerle <fabian@hammerle.me>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import argparse
  18. import filecmp
  19. import logging
  20. import os
  21. import pathlib
  22. import sys
  23. import tempfile
  24. import icalendar
  25. _LOGGER = logging.getLogger(__name__)
  26. def _export_event(event: icalendar.cal.Event, output_dir_path: pathlib.Path) -> None:
  27. temp_fd, temp_path = tempfile.mkstemp(prefix="ics2vdir-", suffix=".ics")
  28. os.write(temp_fd, event.to_ical())
  29. os.close(temp_fd)
  30. output_path = output_dir_path.joinpath("{}.ics".format(event["UID"]))
  31. if not output_path.exists():
  32. _LOGGER.info("creating %s", output_path)
  33. os.rename(temp_path, output_path)
  34. elif not filecmp.cmp(temp_path, output_path):
  35. _LOGGER.info("updating %s", output_path)
  36. os.rename(temp_path, output_path)
  37. else:
  38. _LOGGER.debug("%s is up to date", output_path)
  39. def _main():
  40. logging.basicConfig(
  41. format="%(message)s",
  42. # datefmt='%Y-%m-%dT%H:%M:%S%z',
  43. level=logging.INFO,
  44. )
  45. argparser = argparse.ArgumentParser(
  46. description="Convert iCalendar .ics file to vdir directory."
  47. " Reads from stdin."
  48. )
  49. argparser.add_argument(
  50. "-o",
  51. "--output",
  52. "--output-dir",
  53. default=os.getcwd(),
  54. type=pathlib.Path,
  55. metavar="path",
  56. dest="output_dir_path",
  57. help="Path to output directory (default: current workings dir)",
  58. )
  59. args = argparser.parse_args()
  60. calendar = icalendar.Calendar.from_ical(sys.stdin.read())
  61. _LOGGER.debug("%d subcomponents", len(calendar.subcomponents))
  62. for component in calendar.subcomponents:
  63. if isinstance(component, icalendar.cal.Event):
  64. _export_event(event=component, output_dir_path=args.output_dir_path)
  65. else:
  66. _LOGGER.debug("%s", component)