src/Pure/Tools/imports.scala
author wenzelm
Sun Apr 23 18:47:56 2017 +0200 (2017-04-23)
changeset 65561 741b1d3930c0
parent 65558 479406635409
child 65564 5b3cae328a94
permissions -rw-r--r--
support for Mercurial manifest check;
wenzelm@65557
     1
/*  Title:      Pure/Tools/imports.scala
wenzelm@65518
     2
    Author:     Makarius
wenzelm@65518
     3
wenzelm@65557
     4
Maintain theory imports wrt. session structure.
wenzelm@65518
     5
*/
wenzelm@65518
     6
wenzelm@65518
     7
package isabelle
wenzelm@65518
     8
wenzelm@65518
     9
wenzelm@65526
    10
import java.io.{File => JFile}
wenzelm@65526
    11
wenzelm@65526
    12
wenzelm@65557
    13
object Imports
wenzelm@65518
    14
{
wenzelm@65561
    15
  /* manifest */
wenzelm@65561
    16
wenzelm@65561
    17
  def manifest_files(start: Path, pred: JFile => Boolean = _ => true): List[JFile] =
wenzelm@65561
    18
    Mercurial.find_repository(start) match {
wenzelm@65561
    19
      case None =>
wenzelm@65561
    20
        Output.warning("Ignoring directory " + quote(start.toString) + " (no Mercurial repository)")
wenzelm@65561
    21
        Nil
wenzelm@65561
    22
      case Some(hg) =>
wenzelm@65561
    23
        val start_path = start.file.getCanonicalFile.toPath
wenzelm@65561
    24
        for {
wenzelm@65561
    25
          name <- hg.manifest()
wenzelm@65561
    26
          file = (hg.root + Path.explode(name)).file
wenzelm@65561
    27
          if pred(file) && file.getCanonicalFile.toPath.startsWith(start_path)
wenzelm@65561
    28
        } yield file
wenzelm@65561
    29
    }
wenzelm@65561
    30
wenzelm@65561
    31
wenzelm@65518
    32
  /* update imports */
wenzelm@65518
    33
wenzelm@65526
    34
  sealed case class Update(range: Text.Range, old_text: String, new_text: String)
wenzelm@65526
    35
  {
wenzelm@65526
    36
    def edits: List[Text.Edit] =
wenzelm@65526
    37
      Text.Edit.replace(range.start, old_text, new_text)
wenzelm@65526
    38
wenzelm@65526
    39
    override def toString: String =
wenzelm@65526
    40
      range.toString + ": " + old_text + " -> " + new_text
wenzelm@65526
    41
  }
wenzelm@65526
    42
wenzelm@65526
    43
  def update_name(keywords: Keyword.Keywords, pos: Position.T, update: String => String)
wenzelm@65526
    44
    : Option[(JFile, Update)] =
wenzelm@65526
    45
  {
wenzelm@65526
    46
    val file =
wenzelm@65526
    47
      pos match {
wenzelm@65526
    48
        case Position.File(file) => Path.explode(file).file.getCanonicalFile
wenzelm@65526
    49
        case _ => error("Missing file in position" + Position.here(pos))
wenzelm@65526
    50
      }
wenzelm@65526
    51
wenzelm@65526
    52
    val text = File.read(file)
wenzelm@65526
    53
wenzelm@65526
    54
    val range =
wenzelm@65526
    55
      pos match {
wenzelm@65526
    56
        case Position.Range(symbol_range) => Symbol.Text_Chunk(text).decode(symbol_range)
wenzelm@65526
    57
        case _ => error("Missing range in position" + Position.here(pos))
wenzelm@65526
    58
      }
wenzelm@65526
    59
wenzelm@65526
    60
    Token.read_name(keywords, range.substring(text)) match {
wenzelm@65526
    61
      case Some(tok) =>
wenzelm@65526
    62
        val s1 = tok.source
wenzelm@65526
    63
        val s2 = Token.quote_name(keywords, update(tok.content))
wenzelm@65526
    64
        if (s1 == s2) None else Some((file, Update(range, s1, s2)))
wenzelm@65526
    65
      case None => error("Name token expected" + Position.here(pos))
wenzelm@65526
    66
    }
wenzelm@65526
    67
  }
wenzelm@65526
    68
wenzelm@65526
    69
  def apply_updates(updates: List[(JFile, Update)])
wenzelm@65526
    70
  {
wenzelm@65526
    71
    val file_updates = (Multi_Map.empty[JFile, Update] /: updates)(_ + _)
wenzelm@65526
    72
    val conflicts =
wenzelm@65526
    73
      file_updates.iterator_list.flatMap({ case (file, upds) =>
wenzelm@65526
    74
        Library.duplicates(upds.sortBy(_.range.start),
wenzelm@65526
    75
          (x: Update, y: Update) => x.range overlaps y.range) match
wenzelm@65526
    76
        {
wenzelm@65526
    77
          case Nil => None
wenzelm@65526
    78
          case bad => Some((file, bad))
wenzelm@65526
    79
        }
wenzelm@65526
    80
      })
wenzelm@65526
    81
    if (conflicts.nonEmpty)
wenzelm@65526
    82
      error(cat_lines(
wenzelm@65526
    83
        conflicts.map({ case (file, bad) =>
wenzelm@65526
    84
          "Conflicting updates for file " + file + bad.mkString("\n  ", "\n  ", "") })))
wenzelm@65526
    85
wenzelm@65526
    86
    for ((file, upds) <- file_updates.iterator_list) {
wenzelm@65526
    87
      val edits =
wenzelm@65526
    88
        upds.sortBy(upd => - upd.range.start).flatMap(upd =>
wenzelm@65526
    89
          Text.Edit.replace(upd.range.start, upd.old_text, upd.new_text))
wenzelm@65526
    90
      val new_text =
wenzelm@65526
    91
        (File.read(file) /: edits)({ case (text, edit) =>
wenzelm@65526
    92
          edit.edit(text, 0) match {
wenzelm@65526
    93
            case (None, text1) => text1
wenzelm@65526
    94
            case (Some(_), _) => error("Failed to apply edit " + edit + " to file " + file)
wenzelm@65526
    95
          }
wenzelm@65526
    96
        })
wenzelm@65537
    97
      File.write_backup2(Path.explode(File.standard_path(file)), new_text)
wenzelm@65526
    98
    }
wenzelm@65518
    99
  }
wenzelm@65518
   100
wenzelm@65561
   101
wenzelm@65561
   102
  /* collective operations */
wenzelm@65561
   103
wenzelm@65558
   104
  def imports(
wenzelm@65558
   105
    options: Options,
wenzelm@65561
   106
    operation_manifest: Boolean = false,
wenzelm@65558
   107
    operation_update: Boolean = false,
wenzelm@65558
   108
    progress: Progress = No_Progress,
wenzelm@65558
   109
    selection: Sessions.Selection = Sessions.Selection.empty,
wenzelm@65558
   110
    dirs: List[Path] = Nil,
wenzelm@65558
   111
    select_dirs: List[Path] = Nil,
wenzelm@65558
   112
    verbose: Boolean = false) =
wenzelm@65558
   113
  {
wenzelm@65558
   114
    val full_sessions = Sessions.load(options, dirs, select_dirs)
wenzelm@65558
   115
    val (selected, selected_sessions) = full_sessions.selection(selection)
wenzelm@65558
   116
wenzelm@65558
   117
    val deps =
wenzelm@65558
   118
      Sessions.deps(selected_sessions, progress = progress, verbose = verbose,
wenzelm@65561
   119
        global_theories = full_sessions.global_theories,
wenzelm@65561
   120
        all_known = true)
wenzelm@65561
   121
wenzelm@65561
   122
    if (operation_manifest) {
wenzelm@65561
   123
      progress.echo("\nManifest check:")
wenzelm@65561
   124
      val unused_files =
wenzelm@65561
   125
        for {
wenzelm@65561
   126
          (_, dir) <- Sessions.directories(dirs, select_dirs)
wenzelm@65561
   127
          file <- manifest_files(dir, file => file.getName.endsWith(".thy"))
wenzelm@65561
   128
          if deps.all_known.get_file(file).isEmpty
wenzelm@65561
   129
        } yield file
wenzelm@65561
   130
      unused_files.foreach(file => progress.echo("unused file " + quote(file.toString)))
wenzelm@65561
   131
    }
wenzelm@65558
   132
wenzelm@65558
   133
    if (operation_update) {
wenzelm@65558
   134
      val updates =
wenzelm@65558
   135
        selected.flatMap(session_name =>
wenzelm@65558
   136
        {
wenzelm@65558
   137
          val info = full_sessions(session_name)
wenzelm@65558
   138
          val session_base = deps(session_name)
wenzelm@65558
   139
          val session_resources = new Resources(session_base)
wenzelm@65558
   140
          val imports_resources = new Resources(session_base.get_imports)
wenzelm@65558
   141
wenzelm@65558
   142
          val local_theories =
wenzelm@65558
   143
            (for {
wenzelm@65558
   144
              (_, name) <- session_base.known.theories_local.iterator
wenzelm@65558
   145
              if session_resources.theory_qualifier(name) == info.theory_qualifier
wenzelm@65558
   146
            } yield name).toSet
wenzelm@65558
   147
wenzelm@65558
   148
          def standard_import(qualifier: String, dir: String, s: String): String =
wenzelm@65558
   149
          {
wenzelm@65558
   150
            val name = imports_resources.import_name(qualifier, dir, s)
wenzelm@65558
   151
            val file = Path.explode(name.node).file
wenzelm@65558
   152
            val s1 =
wenzelm@65558
   153
              imports_resources.session_base.known.get_file(file) match {
wenzelm@65558
   154
                case Some(name1) if session_resources.theory_qualifier(name1) != qualifier =>
wenzelm@65558
   155
                  name1.theory
wenzelm@65558
   156
                case Some(name1) if Thy_Header.is_base_name(s) =>
wenzelm@65558
   157
                  name1.theory_base_name
wenzelm@65558
   158
                case _ => s
wenzelm@65558
   159
              }
wenzelm@65558
   160
            val name2 = imports_resources.import_name(qualifier, dir, s1)
wenzelm@65558
   161
            if (name.node == name2.node) s1 else s
wenzelm@65558
   162
          }
wenzelm@65558
   163
wenzelm@65558
   164
          val updates_root =
wenzelm@65558
   165
            for {
wenzelm@65558
   166
              (_, pos) <- info.theories.flatMap(_._2)
wenzelm@65558
   167
              upd <- update_name(Sessions.root_syntax.keywords, pos,
wenzelm@65558
   168
                standard_import(info.theory_qualifier, info.dir.implode, _))
wenzelm@65558
   169
            } yield upd
wenzelm@65558
   170
wenzelm@65558
   171
          val updates_theories =
wenzelm@65558
   172
            for {
wenzelm@65558
   173
              (_, name) <- session_base.known.theories_local.toList
wenzelm@65558
   174
              (_, pos) <- session_resources.check_thy(name, Token.Pos.file(name.node)).imports
wenzelm@65558
   175
              upd <- update_name(session_base.syntax.keywords, pos,
wenzelm@65558
   176
                standard_import(session_resources.theory_qualifier(name), name.master_dir, _))
wenzelm@65558
   177
            } yield upd
wenzelm@65558
   178
wenzelm@65558
   179
          updates_root ::: updates_theories
wenzelm@65558
   180
        })
wenzelm@65558
   181
      apply_updates(updates)
wenzelm@65558
   182
    }
wenzelm@65558
   183
  }
wenzelm@65558
   184
wenzelm@65518
   185
wenzelm@65518
   186
  /* Isabelle tool wrapper */
wenzelm@65518
   187
wenzelm@65518
   188
  val isabelle_tool =
wenzelm@65557
   189
    Isabelle_Tool("imports", "maintain theory imports wrt. session structure", args =>
wenzelm@65518
   190
    {
wenzelm@65518
   191
      var select_dirs: List[Path] = Nil
wenzelm@65561
   192
      var operation_manifest = false
wenzelm@65518
   193
      var requirements = false
wenzelm@65558
   194
      var operation_update = false
wenzelm@65518
   195
      var exclude_session_groups: List[String] = Nil
wenzelm@65518
   196
      var all_sessions = false
wenzelm@65518
   197
      var dirs: List[Path] = Nil
wenzelm@65518
   198
      var session_groups: List[String] = Nil
wenzelm@65518
   199
      var options = Options.init()
wenzelm@65518
   200
      var verbose = false
wenzelm@65518
   201
      var exclude_sessions: List[String] = Nil
wenzelm@65518
   202
wenzelm@65518
   203
      val getopts = Getopts("""
wenzelm@65557
   204
Usage: isabelle imports [OPTIONS] [SESSIONS ...]
wenzelm@65518
   205
wenzelm@65518
   206
  Options are:
wenzelm@65518
   207
    -D DIR       include session directory and select its sessions
wenzelm@65561
   208
    -M           operation: Mercurial manifest check for imported theory files
wenzelm@65518
   209
    -R           operate on requirements of selected sessions
wenzelm@65558
   210
    -U           operation: update theory imports to use session qualifiers
wenzelm@65518
   211
    -X NAME      exclude sessions from group NAME and all descendants
wenzelm@65518
   212
    -a           select all sessions
wenzelm@65518
   213
    -d DIR       include session directory
wenzelm@65518
   214
    -g NAME      select session group NAME
wenzelm@65518
   215
    -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
wenzelm@65518
   216
    -v           verbose
wenzelm@65518
   217
    -x NAME      exclude session NAME and all descendants
wenzelm@65518
   218
wenzelm@65558
   219
  Maintain theory imports wrt. session structure. At least one operation
wenzelm@65558
   220
  needs to be specified (see option -U).
wenzelm@65518
   221
""",
wenzelm@65518
   222
      "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
wenzelm@65561
   223
      "M" -> (_ => operation_manifest = true),
wenzelm@65518
   224
      "R" -> (_ => requirements = true),
wenzelm@65558
   225
      "U" -> (_ => operation_update = true),
wenzelm@65518
   226
      "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
wenzelm@65518
   227
      "a" -> (_ => all_sessions = true),
wenzelm@65518
   228
      "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
wenzelm@65518
   229
      "g:" -> (arg => session_groups = session_groups ::: List(arg)),
wenzelm@65518
   230
      "o:" -> (arg => options = options + arg),
wenzelm@65518
   231
      "v" -> (_ => verbose = true),
wenzelm@65518
   232
      "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
wenzelm@65518
   233
wenzelm@65518
   234
      val sessions = getopts(args)
wenzelm@65561
   235
      if (args.isEmpty || !(operation_manifest || operation_update))
wenzelm@65561
   236
        getopts.usage()
wenzelm@65518
   237
wenzelm@65518
   238
      val selection =
wenzelm@65518
   239
        Sessions.Selection(requirements, all_sessions, exclude_session_groups,
wenzelm@65518
   240
          exclude_sessions, session_groups, sessions)
wenzelm@65518
   241
wenzelm@65518
   242
      val progress = new Console_Progress(verbose = verbose)
wenzelm@65518
   243
wenzelm@65561
   244
      imports(options, operation_manifest = operation_manifest, operation_update = operation_update,
wenzelm@65561
   245
        progress = progress, selection = selection, dirs = dirs, select_dirs = select_dirs,
wenzelm@65561
   246
        verbose = verbose)
wenzelm@65518
   247
    })
wenzelm@65518
   248
}