RemoveTask.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env python3
  2. # Contest Management System - http://cms-dev.github.io/
  3. # Copyright © 2013-2018 Stefano Maggiolo <s.maggiolo@gmail.com>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (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 Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. """Utility to remove a task.
  18. """
  19. import argparse
  20. import sys
  21. from cms import utf8_decoder
  22. from cms.db import SessionGen, Task
  23. def ask(task_name):
  24. ans = input("This will delete task `%s' and all related data, including "
  25. "submissions. Are you sure? [y/N] "
  26. % task_name).strip().lower()
  27. return ans in ["y", "yes"]
  28. def remove_task(task_name):
  29. with SessionGen() as session:
  30. task = session.query(Task)\
  31. .filter(Task.name == task_name).first()
  32. if not task:
  33. print("No task called `%s' found." % task_name)
  34. return False
  35. if not ask(task_name):
  36. print("Not removing task `%s'." % task_name)
  37. return False
  38. num = task.num
  39. contest_id = task.contest_id
  40. session.delete(task)
  41. # Keeping the tasks' nums to the range 0... n - 1.
  42. if contest_id is not None:
  43. following_tasks = session.query(Task)\
  44. .filter(Task.contest_id == contest_id)\
  45. .filter(Task.num > num)\
  46. .all()
  47. for task in following_tasks:
  48. task.num -= 1
  49. session.commit()
  50. print("Task `%s' removed." % task_name)
  51. return True
  52. def main():
  53. """Parse arguments and launch process.
  54. """
  55. parser = argparse.ArgumentParser(
  56. description="Remove a task from the database."
  57. )
  58. parser.add_argument(
  59. "task_name",
  60. action="store", type=utf8_decoder,
  61. help="short name of the task"
  62. )
  63. args = parser.parse_args()
  64. success = remove_task(task_name=args.task_name)
  65. return 0 if success is True else 1
  66. if __name__ == "__main__":
  67. sys.exit(main())